Here are the complete code to export data table into excel file:
protected void btnExport_Click(object sender, ImageClickEventArgs e)
{
DataTable dt=clsUser.getAllData("select * from <table_Name>");
ExportToExcel(dt);
}
public void ExportToExcel(DataTable dt)
{
if (dt.Rows.Count > 0)
{
string filename = "Books.xls";
string excelHeader ="Books Report";
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();
// Report Header
hw.WriteLine("<b><u><font size=’3′> " + excelHeader + " </font></u></b>");
//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();
}
}
No comments:
Post a Comment