How to export GridView to an Excel file

To export GridView data to an Excel file, follow these steps:

  1. In the page that contains the GridView control, override the VerifyRenderingInServerForm method. This lets you programmatically render the GridView control without rendering the complete page. The default implementation of this method prevents you from rendering the GridView control separately.

  2. Make sure that the GridView control is inside a form element that contains the attribute runat=”server”.

The following example shows the code that is required in order to render the GridView control as an Excel spreadsheet.

protected void Button1_Click(object sender, System.EventArgs e)  

{  

// Clear the response.

    Response.Clear();  

// Set the type and file.name.

    Response.AddHeader(“content-disposition”,  

“attachment;filename=FileName.xls”);  

    Response.Charset = “”;  

    Response.ContentType = “application/vnd.xls”;  

// Add the HTML from the GridView control to a StringWriter instance so you  

    //   can write it out later.

    System.IO.StringWriter sw = new System.IO.StringWriter();  

    System.Web.UI.HtmlTextWriter hw = new HtmlTextWriter(sw);  

    GridView1.RenderControl(hw);  

// Write the data.

    Response.Write(sw.ToString);  

    Response.End();  

}  

public override void VerifyRenderingInServerForm(Control control)  

{  

}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s