In one of my previous article Exporting GridView to Text Files I talked about how you can export GridView to text files. The problem with using text files is that you cannot control the format and it gets really messy if you have more columns. In this article I will explain how you can export your GridView control to Excel files. If you are working with Datagrid than you can also check out my article Exporting Datagrid to Excel, Text and Word Files.

 

Introduction:

In one of my previous article Exporting GridView to Text Files I talked about how you can export GridView to text files. The problem with using text files is that you cannot control the format and it gets really messy if you have more columns. In this article I will explain how you can export your GridView control to Excel files. If you are working with Datagrid than you can also check out my article Exporting Datagrid to Excel, Text and Word Files.

Exporting GridView to Excel Files: 

The approach is pretty much the same as it was in Datagrid. The following code executes on a button click event.

Response.Clear();

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

Response.Charset = "";

// If you want the option to open the Excel file without saving than

// comment out the line below

// Response.Cache.SetCacheability(HttpCacheability.NoCache);

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

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

System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);

gvMaster.RenderControl(htmlWrite);

Response.Write(stringWrite.ToString());

Response.End();

The code is almost identical to what we used when exporting Datagrid (see here). If you run this code it will not work the reason is that we need to tell ASP.NET that there is a control in our form that will be rendered at runtime. For this you can just override the Page.VerifyRenderingInServerForm method.

public override void VerifyRenderingInServerForm(Control control)

{

// Confirms that an HtmlForm control is rendered for the specified ASP.NET server control at run time.

}

Now if you try to export your GridView to excel it will work fine.

I hope you like the article, happy coding !