Sunday, November 22, 2009

Export dataset to excel in c#

The following function exports dataset to excel in c#

public static void Convertexcel(DataTable dt, HttpResponse Response)
{
try
{
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=Product.xls");
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.ms-excel";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new System.Web.UI.HtmlTextWriter(stringWrite);
System.Web.UI.WebControls.DataGrid dg = new System.Web.UI.WebControls.DataGrid();
dg.DataSource = dt;
dg.DataBind();
dg.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
}
catch (Exception err)
{
throw err;
}
}

No comments:

Post a Comment