C# Export Data Table to Excel
C# Export Data Table to Excel
objCmd = new SqlCommand(vSQLStr, CN);
SqlDataAdapter da = new SqlDataAdapter(objCmd);
DataTable dt = new DataTable();
da.Fill(dt);
DataGrid dg = new DataGrid();
dg.DataSource = dt;
dg.DataBind();
ExportToExcel("test.xls", dg);
dg = null;
dg.Dispose();
private void ExportToExcel(string strFileName, DataGrid dg)
{
Response.ClearContent();
Response.AddHeader("content-disposition", "attachment; filename=" + strFileName);
Response.ContentType = "application/excel";
System.IO.StringWriter sw = new System.IO.StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
dg.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}
SqlDataAdapter da = new SqlDataAdapter(objCmd);
DataTable dt = new DataTable();
da.Fill(dt);
DataGrid dg = new DataGrid();
dg.DataSource = dt;
dg.DataBind();
ExportToExcel("test.xls", dg);
dg = null;
dg.Dispose();
private void ExportToExcel(string strFileName, DataGrid dg)
{
Response.ClearContent();
Response.AddHeader("content-disposition", "attachment; filename=" + strFileName);
Response.ContentType = "application/excel";
System.IO.StringWriter sw = new System.IO.StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
dg.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}
Permissions in this forum:
You cannot reply to topics in this forum