Tuesday, September 14, 2010

Export to Excel in ASP.Net 2.0 – Gridview to Excel, DataTable to Excel

Exporting contents to excel or preparing a excel report of the data displayed on a webpage is one of the most common tasks in real world web applications. Most frequently, we will export the contents of GridView control to excel. In this article, i will implement some of the common ways of exporting a table of data displayed on a web page to a excel file.

Export to Excel
Ø       Rendering the Gridview Control to Excel
Ø       Rendering the underlying DataTable to Excel

Rendering the Gridview Control to Excel
This is one of the most commonly done approach where we set MIME type and use Gridview’s RenderControl() method, similar to we do for a Datagrid control.
        string attachment = "attachment; filename=Employee.xls";
        Response.ClearContent();
        Response.AddHeader("content-disposition", attachment);
        Response.ContentType = "application/ms-excel";
        StringWriter stw = new StringWriter();
        HtmlTextWriter htextw = new HtmlTextWriter(stw);
        gvEmployee.RenderControl(htextw);
        Response.Write(stw.ToString());
        Response.End();

When we execute the above code, it will give the following error.


view more : http://www.codedigest.com/Articles/ASPNET/130_Export_to_Excel_in_ASPNet_20_%E2%80%93Gridview_to_Excel_DataTable_to_Excel.aspx