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.
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)'”
kisi,
my script relies on two controls in the aspx file, FormView1 and GridView1. These are the object references you are missing.
is it possible to use this script to generate some report ? like matrix and not only a statistic
Hi
Excellent use of using excel with asp.net – do you have a working example I could download please