Tuesday, March 23, 2010

Export GridView to Excel

DataSet ds = new DataSet();
GridView gv = new GridView();
gv.DataSource = ds;
gv.AllowPaging = false;
gv.DataBind();

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 stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
gv.RenderControl(htmlWrite);

Response.Write(stringWrite.ToString());
Response.End();

There are some limitation on the above method.

the limitations of having to turn off event validation or override any page methods. This gives the freedom to put these methods were you want them ( within a static GridViewExportUtil class) without having to worry about the page that hosts the GridView doing anything special.


http://mattberseth.com/blog/2007/04/export_gridview_to_excel_1.html

No comments: