Introduction
Export the Datatable records to Excel sheet in C#.net
Using the code
This below function used to generate excel file based on datatable.
public void ExportToExcel(DataTable dt)
{
if (dt.Rows.Count > 0)
{
string filename = "DownloadMobileNoExcel.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();
dgGrid.RenderControl(hw);
Response.ContentType = "application/vnd.ms-excel";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + "");
this.EnableViewState = false;
Response.Write(tw.ToString());
Response.End();
}
}
Call the above function in button click event
protected void btnSave_Click(object sender, EventArgs e)
{
ExportToExcel((DataTable)ViewState["gvMobile"]);
}
public override void VerifyRenderingInServerForm(Control control)
{
}
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.