Monday, April 14, 2008

How to Export Gridview data to Excel

The following line of codes will help you export data in Gridview to Excel without using Excel COM or third party components:

private void ExportGridtoExcel()
{

Response.Clear();
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("content-disposition", "attachment;filename=OverviewReport.xls");

System.IO.StringWriter objStringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter objHTMLTextWriter = new HtmlTextWriter
(objStringWriter);

GridView objGridView = new GridView();
// set the page size to a number that will show all data of the gridview in one page since this
// functionality is dependend on how many data are visible on the first page on the gridview
objGridView.PageSize = 1000;
objGridView.AllowPaging = false;
objGridView.DataSource = dt;
objGridView.DataBind();
objGridView.RenderControl(objHTMLTextWriter);

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

}