Export SQL Table Data into Excel using C#.Net Application

This article provides a brief knowledge to get your data in excel sheet.

public void ExportData(DataTable dset)

{

HttpResponse response = HttpContext.Current.Response;

// first let's clean up the response.object

response.Clear();

response.Charset = "";

// set the response mime type for excel

//Dim filename As String = "Record.xls"

string filename = "Report(" + "" + DateTime.Now.ToString("dd-MM-yyyy") + ").xls";

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 = dset;

dg.DataBind();

dg.RenderControl(htw);

response.Write(sw.ToString());

response.End();

}

}

}

To export data in excel just call above method and pass your datatable into this method.