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();
}
}
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: