Export GridView contents to MS-Excel

Export GridView contents to MS-Excel

The following code can be used to export the contents of gridview control to excel format. Consider for example if the gridview columns are populated from a database table and to export these data to excel the following code can be used.

protected void Export_GridView(object sender, EventArgs e)
{
        string attachment = “attachment; filename=Report.xls”;
        Response.ClearContent();
        Response.AddHeader(”content-disposition”, attachment);
        Response.ContentType = “application/ms-excel”;
        StringWriter writer = new StringWriter();
        HtmlTextWriter htmlwriter = new HtmlTextWriter(writer);
        GridView1.RenderControl(htmlwriter);
        Response.Write(writer.ToString());
        Response.End();
   
}

when using the above code the application might throw an error as

Control ‘GridView1′ of type ‘GridView’ must be placed inside a form tag with runat=server.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Web.HttpException: Control ‘GridView1′ of type ‘GridView’ must be placed inside a form tag with runat=server.

To avoid this use the following code

public override void VerifyRenderingInServerForm(Control control)
{

}

When the above function is called a File Download dialog box will be shown asking to open or save the file Report.xls. Thus the gridview contents are exported to excel.

Leave a Reply

You must be logged in to post a comment.


All material @ copyrighted by chrisranjana.com. If you want to link to this article you are welcome to do so. Unauthorized publication is strictly prohibited. This developer tutorial website contains articles by Php programmers , Software developers, Mysql programmers and asp c# programmers. This website also contains ajax tutorials and advanced mysql sql stored procedures and functions tutorials and sample codes.