ASP.NET Export content to Excel files.

The most common problem during exporting page content to an excel file is the following exception: RegisterForEventValidation can only be called during Render();
The only thing you need to do is to set enableEventValidation ="false" in web.config (affects all your pages) or in the head page line.

If you want to render a control into an excel file (using HTML representation) the VerifyRenderingInServerForm() method must be overridden.

public override void VerifyRenderingInServerForm(Control control){}

This confirms that an HtmlForm control is already rendered.

... and the example - rendering existing gridview control into a xls file:
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=file.xls");
Response.Charset = "";
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);
htmlWrite.Write("text text");
htmlWrite.WriteBreak();
GridView1.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();

No comments:

Post a Comment