Pages

Tuesday 3 January 2012

Exporting DataGrid to Excel in asp.net

using RKLib.ExportData;


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);
myDataGrid.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();

Here,
Response.AddHeader:  is letting ASP.NET know that we are exporting to a file which is named FileName.xls.
Response.ContentType:   denotes the type of the file being exported.
myDataGrid.RenderControl(htmlWrite)  writes the data to the HtmlTextWriter.
Response.Write(stringWrite.ToString());  sends the request to the response stream.

1 comment:

  1. Great article

    We can also submit our .net related article link on http://www.dotnettechy.com to increase the website traffic

    ReplyDelete