Export Gridview to Excel in Asp.Net.


Gridview to Excel

HtmlForm HtmlForm = new HtmlForm();
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
string attachment;
attachment = "attachment; filename=Export.xls";
Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/Vnd.ms-excel";
Response.Charset = "";
Response.AddHeader("content-disposition", attachment);
//grdVerifierPerformance is the gridview to export
grdVerifierPerformance.GridLines = GridLines.Both;
grdVerifierPerformance.RenderControl(htmlWrite);
Response.Write(stringWrite);
Response.End();

If you are using master page in your page then add below line in your code

public override void VerifyRenderingInServerForm(System.Web.UI.Control control)
    {
        // Do NOT call MyBase.VerifyRenderingInServerForm
    }