Generate Excel sheets from your ASP.Net page

A web application that I develop allows the user to generate some statistics.

A FormView component contains all the selection criteria to generate the statistics, and a GridView displays the results provided by a stored procedure.

The next step was to allow the user to download this data into Excel.

I used a linkbutton to invoke the creation of the Excel sheet. The click event handler looks like this:

System.Text.StringBuilder sb = new System.Text.StringBuilder();
System.IO.StringWriter wr = new System.IO.StringWriter(sb);
HtmlTextWriter htw = new HtmlTextWriter(wr);

Response.ContentType = "application/";
Response.AddHeader("Content-Disposition", "attachment;filename=statistics.xls");
Response.AddHeader("Content-Encoding", Response.ContentEncoding.EncodingName);
<meta http-equiv=""Content-Type"" content=""text/html; charset=UTF-8"">
.id { font-weight: bold; }

Additionally, one has to suppress the built-in check whether the asp controls are within a form tag, since our Excel sheet does not contain a form tag:

public override void VerifyRenderingInServerForm (Control control)
// do nothing

That’s it.

4 thoughts on “Generate Excel sheets from your ASP.Net page

  1. i already tried the script but there is some error, which is like this “An object reference is required for the nonstatic field, method, or property ‘System.Web.UI.Control.RenderControl(System.Web.UI.HtmlTextWriter)'”

Leave a Reply

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

You are commenting using your 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 )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.