Very simple and based on the one I blogged about previously (well not based on the code but based on the same idea). Anyway, hook this up to a link button, pass in a dataset and it'll provide a downloadable Excel compatible file...
public class GetExcel
{
public static void Convert(DataSet ds, int dataTableId, HttpResponse response, string fileName)
{
DataGrid dg = new DataGrid();
dg.DataSource = ds.Tables[dataTableId];
dg.DataBind();
response.Buffer = true;
response.ContentType="application/vnd.ms-excel";
response.AddHeader("Content-Disposition", "attachment;filename=" + fileName) ;
using(StringWriter sw = new StringWriter())
{
using(HtmlTextWriter writer = new HtmlTextWriter(sw))
{
dg.RenderControl(writer);
response.Write(sw.ToString());
}
}
response.End();
}
public static void Convert(DataSet ds, int dataTableId, HttpResponse response)
{
Convert(ds,dataTableId,response,"report.xls");
}
public static void Convert(DataSet ds, HttpResponse response)
{
Convert(ds,0,response);
}
}
© 2025 Scott Galloway — Unlicense — All content and source code on this site is free to use, copy, modify, and sell.