In this article we are learning how to datatable export to excel file.
In Below function we have to pass datatable and file Name it will create execl file.
protected void ExportExcelByDataTable(DataTable dt,String FileName)
{
Response.Clear();
Response.Buffer = true;
Response.ClearContent();
Response.ClearHeaders();
Response.Charset = "UTF-8";
Response.ContentEncoding = System.Text.Encoding.UTF8;
string FileNameNew = FileName + DateTime.Now.ToString("ddMMyyyyhhmmss") + "xls";
StringWriter strwritter = new StringWriter();
HtmlTextWriter htmltextwrtter = new HtmlTextWriter(strwritter);
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", "attachment;filename=" + FileNameNew);
string tab = "";
foreach (DataColumn dc in dt.Columns)
{
Response.Write(tab + dc.ColumnName);
tab = "\t";
}
Response.Write("\n");
int i;
foreach (DataRow dr in dt.Rows)
{
tab = "";
for (i = 0; i < dt.Columns.Count; i++)
{
Response.Write(tab + dr[i].ToString());
tab = "\t";
}
Response.Write("\n");
}
Response.End();
}
No comments:
Post a Comment
Please do not enter any spam link in the comment box.