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);
FormView1.RenderControl(htw);
GridView1.RenderControl(htw);
htw.Flush();

Response.Clear();
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", "attachment;filename=statistics.xls");
Response.AddHeader("Content-Encoding", Response.ContentEncoding.EncodingName);
Response.Write(
@"<html><head>
<meta http-equiv=""Content-Type"" content=""text/html; charset=UTF-8"">
<style>
.id { font-weight: bold; }
</style>
</head>
<body>
");
Response.Write(sb.ToString());
Response.Write("</body></html>");
Response.End();

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:

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 )

Connecting to %s

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