﻿# Dumb little thing...class which outputs an Excel compatible table from a DataSet

<datetime class="hidden">2004-03-26T00:00</datetime>
<!-- category -- mostlylucidcouk, Imported, ASP.NET, C# -->

Very simple and based on the [one I blogged about previously](/posts/872.aspx) (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); 

} 

}