How can I export a
DataTable
to Excel in C#? I am using Windows Forms. The DataTable
is associated with a DataGridView
control. I have to export records of DataTable
to Excel.C# is a multi-paradigm programming language encompassing strong typing, imperative, declarative, functional, generic, object-oriented (class-based), and component-oriented programming disciplines. It was developed by Microsoft, and is one of the programming languages designed for the Common
The following are the codes used to export data from database to excel in c#
Double click on the button and paste the codes below.
Note: It is a must to use the library below
=======================================================================
using Excel = Microsoft.Office.Interop.Excel;
====================================================================
int rowsTotal = 0;
int colsTotal = 0;
int I = 0;
int j = 0;
int iC = 0;
System.Windows.Forms.Cursor.Current =
System.Windows.Forms.Cursors.WaitCursor;
Excel.Application xlApp = new Excel.Application();
try
{
Excel.Workbook excelBook =
xlApp.Workbooks.Add();
Excel.Worksheet excelWorksheet =
(Excel.Worksheet)excelBook.Worksheets[1];
xlApp.Visible = true;
rowsTotal = dataGridView1.RowCount - 1;
colsTotal = dataGridView1.Columns.Count - 1;
var
_with1 = excelWorksheet;
_with1.Cells.Select();
_with1.Cells.Delete();
for (iC = 0; iC <= colsTotal; iC++)
{
_with1.Cells[1, iC + 1].Value = dataGridView1.Columns[iC].HeaderText;
}
for (I = 0; I <= rowsTotal - 1; I++)
{
for (j = 0; j <= colsTotal; j++)
{
_with1.Cells[I + 2, j +
1].value = dataGridView1.Rows[I].Cells[j].Value;
}
}
_with1.Rows["1:1"].Font.FontStyle
= "Bold";
_with1.Rows["1:1"].Font.Size
= 12;
_with1.Cells.Columns.AutoFit();
_with1.Cells.Select();
_with1.Cells.EntireColumn.AutoFit();
_with1.Cells[1, 1].Select();
}
catch (Exception
ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
finally
{
//RELEASE ALLOACTED RESOURCES
System.Windows.Forms.Cursor.Current =
System.Windows.Forms.Cursors.Default;
xlApp = null;
}
===================================================================