Friday, March 13, 2009

How to Exporting DataGrid to Excel in c#

Exporting DataGrid to Excel might not need any excel object model in asp.net application with datagrid. Below is the complete code to export the Datagrid value to Excel in C#.


Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=FileName.xls");
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.xls";

System.IO.StringWriter swtext = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hwtext = new HtmlTextWriter(swtext);

DGexcel.RenderControl(hwtext);
Response.Write(swtext.ToString());
Response.End();

Response.AddHeader is to know that we are exporting to a file which is named FileName.xls.

Response.ContentType is the type of the file being exported.

DGexcel.RenderControl(hwtext) writes the data to the HtmlTextWriter.

Response.Write(swtext.ToString()) sends the request to the response stream.

Labels:

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home