Wednesday, November 19, 2008

Exporting a DataSet to Excel using C#

Here's a quick way to Export your DataSet to Excel.
Just throw a quick LinkButton on your Front End with an OnClick="ExportResults"
___________________________________________________________
Code Behind:
protected void ExportResults(object sender, EventArgs e)
{
string filename = String.Format("Concatenated_Results_{0}_{1}.xls", DateTime.Today.Month.ToString(), DateTime.Today.Year.ToString());

Response.Clear();
Response.AddHeader("Content-Disposition", "attachment;filename=" + filename);
Response.Charset = "";

// SetCacheability doesn’t seem to make a difference (see update)
Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);

Response.ContentType = "application/vnd.xls";

System.IO.StringWriter stringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);

// Throws exception: Control ‘ComputerGrid’ of type ‘GridView’
// must be placed inside a form tag with runat=server.
// ComputerGrid.RenderControl(htmlWrite);

// Alternate to ComputerGrid.RenderControl above
System.Web.UI.HtmlControls.HtmlForm form = new System.Web.UI.HtmlControls.HtmlForm();
Controls.Add(form);
form.Controls.Add(GridResults);
form.RenderControl(htmlWriter);

Response.Write(stringWriter.ToString());
Response.End();

}