Tuesday, January 29, 2008

Export HTML controls to MS EXCEL

You need to have few simple steps to do this. You can just add a header to say that the page should output in excel format. But it is not effective since it will corrupt most of the time when the size is growing over 100kb. This way it allows you to output itas Binary. The other difference is this way you can output only the control you need. Not the whole page.

Step 1: Just copy paste the following method in to your page. This is just to allow the rendering engine to identify your control as a valid control. Dont do any change to this.

public override void VerifyRenderingInServerForm(Control control)
{
// Confirms that an HtmlForm control is rendered for the
// specified ASP.NET server control at run time.
}

Step 2: Add the code to your export button click event. Keep in mind to activate "ViewState" for the control. Note that "ReportTable" is the control I'm using.

protected void Export_Click(object sender, EventArgs e)
{
try
{
Response.Clear();
Response.ContentType = "application/vnd.ms-excel";
Response.Charset = "";
this.EnableViewState = false;

Response.AddHeader("content-disposition", "attachment;filename=Report.xls");
Response.Charset = ""; 

Response.ContentType = "application/vnd.xls";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
//GridView1.RenderControl(htmlWrite);
ReportTable.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
}
catch (System.Threading.ThreadAbortException ev)
{
// Do nothing - This is comming from "Response.End();"
}
catch (Exception ex)
{
// Log any error message
}
}