Export ASP.NET GridView to Excel

In the  button click event handler  code :



protected void btnExcel_Click(object sender, EventArgs e)
        {
            Response.Clear();


            Response.AddHeader("content-disposition", "attachment; filename=Product.doc");
            Response.Charset = "";


            Response.ContentType = "application/vnd.doc";


            StringWriter stringWriter = new StringWriter();
            HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);


            GridView1.RenderControl(htmlWriter);
            Response.Write(stringWriter.ToString());


            Response.End();
        }

But you can use similar code to export to other formats by changing the ContentType property.  
( Response.ContentType = "application/vnd.doc";) and filename (filename=Product.doc")



Sometimes, when you render any asp.net control dynamically as I am doing with the GridView control , you can get HttpException with the following message:

Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server.



The problem can be solved by overriding Page class VerifyRenderingInServerForm method which confirms that an HtmlForm control is rendered for the specified ASP.NET server control at run time.

public override void VerifyRenderingInServerForm(Control control)

{ }



















Comments

Popular posts from this blog

How to retain the data annotations or class during modify a table in the database

Interview Questions

AJAX CONTROL