Nowadays in many web application, we need to display the contents of a dataset into an excel file, so that all records can be viewed by the user.
The below method will provide a solution to this requirement.
All the user needs to do is call the method specifying the dataset and the filename.
eg:-
ExportDataSetToExcel(dsEmployeeDetails,"EmpDetails .xls");
Note : This is not applicable for Microsoft Office 2007 and above
Code:
/// <summary>
/// To Export data Set to Excel
/// </summary>
/// <param name="ds"></param>
/// <param name="filename"></param>.
public void ExportDataSetToExcel(DataSet ds, string filename)
{
HttpResponse response = HttpContext.Current.Response;
// first let's clean up the response.object
response.Clear();
response.Charset = "";
// set the response mime type for excel
response.ContentType = "application/vnd.ms-excel";
response.AddHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");
// create a string writer
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
// instantiate a datagrid
DataGrid dg = new DataGrid();
dg.DataSource = ds.Tables[0];
dg.DataBind();
dg.RenderControl(htw);
response.Write(sw.ToString());
response.End();
}
}
}




