In this post we will be exporting the DataTable to an Excel using C#
Below is the method which will do the trick. Just pass the parameters datatable and the filename.
}
Hope this helps...
Below is the method which will do the trick. Just pass the parameters datatable and the filename.
private void ExportDataTableToExcel(DataTable thetable, string fileName)
{
string attachment = "attachment; filename=" + fileName + ".xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/vnd.ms-excel";
//write columns from DataTable to Excel
string tab = "";
foreach (DataColumn dc in thetable.Columns)
{
string title = string.Empty;
if (dc.ColumnName.Contains("Meta"))
title = "Metadata Properties";
else
title = dc.ColumnName;
Response.Write(tab + title);
tab = "\t";
}
Response.Write("\n");
//write rows from DataTable to Excel
int i;
foreach (DataRow dr in thetable.Rows)
{
tab = "";
for (i = 0; i < thetable.Columns.Count; i++)
{
Response.Write(tab + dr[i].ToString());
tab = "\t";
}
Response.Write("\n");
}
//To throw the excel file generated
Response.End();
Hope this helps...