Click here to Skip to main content
15,896,606 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,
How to add header in excel while importing any datatable into excel.
I am using this function to Import to excel

public void ExportToExcel(DataTable dt)
{
if (dt.Rows.Count > 0)
{
string filename = "PatientList.xls";
System.IO.StringWriter tw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
DataGrid dgGrid = new DataGrid();
dgGrid.DataSource = dt;
dgGrid.DataBind();

//Get the HTML for the control.
dgGrid.RenderControl(hw);
//Write the HTML back to the browser.
//Response.ContentType = application/vnd.ms-excel;
Response.ContentType = "application/vnd.ms-excel";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + "");
this.EnableViewState = false;
Response.Write(tw.ToString());
Response.End();
}
}
Posted
Comments
Rohit R Chavan 27-Nov-14 1:58am    
have you looked this post on CP

http://www.codeproject.com/Articles/406704/Export-DataTable-to-Excel-with-Formatting-in-Cshar
srishti_ 27-Nov-14 6:38am    
thanks

Add the below code, you will get header.

Response.AppendHeader("Content-Disposition", sheetname);
 
Share this answer
 
Export Data to Excel from DataTable[^]

Go through this link.

C#
// column headings
for (int i = 0; i < Tbl.Columns.Count; i++)
{
workSheet.Cells[1, (i + 1)] = Tbl.Columns[i].ColumnName;
}

 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900