Saturday, January 4, 2014

Export / Output asp net gridview output to excel file

If you want to export gridview output to an excel file you can use the following code.
In this example it is done by clicking a button
Requirements
  1. GridView with ID GridView1
  2. ASP NET Button With ID Button1
    protected void Button1_Click(object sender, EventArgs e)
    {
        string filename = "Bingo.xls";
        ExportToExcel(filename, GridView1);
    }
     
    private void ExportToExcel(string filename, GridView gv)
    {
        Response.ClearContent();
        Response.AppendHeader("content-disposition""attachment; filename=" + filename);
        Response.Charset = "";
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.ContentType = "application/vnd.ms-excel";
        System.IO.StringWriter stringWriter = new System.IO.StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(stringWriter);
        gv.RenderControl(htw);
        Response.Write(stringWriter.ToString());
        Response.End();
    }
Half way there Don't forget to override VerifyRenderingInServerForm
public override void VerifyRenderingInServerForm(Control control)
{
    /* Verifies that the control is rendered */
}
All done.

No comments:

Post a Comment