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 Responses to Generate Excel sheets from your ASP.Net page

  1. kisi says:

    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)'”

  2. devio says:

    my script relies on two controls in the aspx file, FormView1 and GridView1. These are the object references you are missing.

  3. kisi says:

    is it possible to use this script to generate some report ? like matrix and not only a statistic

  4. Eugene says:


    Excellent use of using excel with – do you have a working example I could download please

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 )

Google+ photo

You are commenting using your Google+ 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.

%d bloggers like this: