Tuesday, April 5, 2011

Data Export to Excel From Grid


protected void ExportToExcelFromGrid()
    {
        try
        {
            String fname = "attachment; filename=Lion.xls";
            Response.ClearContent();
            Response.AddHeader("content-disposition", fname);
            Response.ContentType = "application/ms-excel";
            System.IO.StringWriter sw1 = new System.IO.StringWriter();
            System.IO.StringWriter sw = new System.IO.StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);
            HtmlTextWriter htw1 = new HtmlTextWriter(sw1);
            GridView1.RenderControl(htw);
            GridView1.RenderControl(htw1);
            Response.Write(sw.ToString());
            Response.End();
        }
        catch (Exception ex)
        {
            //logToFile("Error : " + EX.ToString());
        }

    }
    public override void VerifyRenderingInServerForm(Control control)
    {

    }

Overriding VerifyRenderingInServerForm Event in the page
Adding this event in the codebehind confirms that an HtmlForm control is rendered for the specified ASP.NET server control at run time.



Rendering the underlying DataTable to Excel
This is one of the easiest ways of exporting the data to excel.  The content of the DataTable should be written to the response by setting ContentType attribute to "application/vnd.ms-excel" and by setting its header.

No comments:

Post a Comment