There are various ways to export data to excel, such as:
1. Write As XML with .XLS extensions
2. Render DataTable as Excel
3. Uisng HtmlForm object
4. Using VerifyRenderingInServerForm
Insha Allah, I will discuss all these export types gradually. Today I want to discuss here how to export DataTable to Excel. Its very simple ,I write down a method here just call it ana pass your DataTable as a parameter then this method generate a Excel file for you.
Code:
public void ExportDataTable(DataTable dt)
{
string attachment = "attachment; filename=" + FileName.xls + "";
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader("content-disposition", attachment);
HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
string sTab = "";
foreach (DataColumn dc in dt.Columns)
{
HttpContext.Current.Response.Write(sTab + dc.ColumnName);
sTab = "\t";
}
HttpContext.Current.Response.Write("\n");
int i;
foreach (DataRow dr in dt.Rows)
{
sTab = "";
for (i = 0; i < dt.Columns.Count; i++)
{
HttpContext.Current.Response.Write(sTab + dr[i].ToString());
sTab = "\t";
}
HttpContext.Current.Response.Write("\n");
}
HttpContext.Current.Response.End();
}
2 comments:
Yes indeed very nice article. Many many thanks for this.
Yes indeed very nice article. Many many thanks for this.
Post a Comment