Refactor Code

  • Gravatar
    Export GridView to Excel

    by azamsharp on 5/12/2008 2:27:20 PM
  • Here is some code that I use to export GridView to excel.

  • // inside the button click event

    Response.ClearContent();

    Response.AddHeader("content-disposition", "attachment; filename=MyExcelFile.xls");

    Response.ContentType = "application/excel";

    StringWriter sw = new StringWriter();

    HtmlTextWriter htw = new HtmlTextWriter(sw);

    gvUsers.RenderControl(htw);

    Response.Write(sw.ToString());

    Response.End();

    // end of the button click event!

    // leave this method empty!
    public override void VerifyRenderingInServerForm(Control control)

    {

    }

  • Refactor it!
  • Gravatar
    You can also export the formatting for the GridView control. These formatting will allow you to view the data correctly in the excel file.
    by azamsharp on 5/12/2008 2:28:25 PM
  • protected void Btn_ExportClick(object sender, EventArgs e)

    {

    string style = @"<style> .text { mso-number-format:\@; } </style> ";

    Response.ClearContent();

    Response.AddHeader("content-disposition", "attachment; filename=MyExcelFile.xls");

    Response.ContentType = "application/excel";

    StringWriter sw = new StringWriter();

    HtmlTextWriter htw = new HtmlTextWriter(sw);

    gvUsers.RenderControl(htw);

    // Style is added dynamically

    Response.Write(style);

    Response.Write(sw.ToString());

    Response.End();

    }

    public override void VerifyRenderingInServerForm(Control control)

    {

    }
Please log in to refactor the code! Login