Datatable to Excel file without using a loop


Hello,

Using below function you can  get excel file from you datatable ,as yes without using any for or foreach loop


public void ExportToExcel(DataTable dt, 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.ContentType = "application/vnd.xls";
response.AddHeader("Content-Disposition", "attachment;filename=TestingReports.xls");

// create a string writer
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
// instantiate a datagrid
DataGrid dg = new DataGrid();
dg.DataSource = dt;
dg.DataBind();
dg.RenderControl(htw);
response.Write(sw.ToString());
response.End();
}
}
}

Leave a comment