Uderc programming article aggregator sites

How to export a dynamically generated datatable into excel sheet 2013?

Advertisement
I have one data table and in that data table i am fetching data from sharepoint 2013 lists.
When I export that data table into excel sheet, what ever data is static will be shown but the data which I fetch from lists are not coming.
How should I get that data in my excel sheet from that data table?
This is the code for Export to Excel:
public void ExportToExcel(DataTable dt)
if (dt.Rows.Count > 0)
string filename = "WebTrafficReport.xls";
System.IO.StringWriter tw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
DataGrid dgGrid = new DataGrid();
dgGrid.DataSource = dt;
dgGrid.DataBind();
//Get the HTML for the control.
dgGrid.RenderControl(hw);
//Write the HTML back to the browser.
//Response.ContentType = application/vnd.ms-excel;
Response.ContentType = "application/vnd.ms-excel";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + "");
this.EnableViewState = false;
Response.Write(tw.ToString());
Response.End();
Thanks in Advance.
Advertisement
The best answer: ublic void ExportToExcel(DataTable dt)
if (dt.Rows.Count > 0)
string filename = "WebTrafficReport.xls";
System.IO.StringWriter tw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
DataGrid dgGrid = new DataGrid();
dgGrid.DataSource = dt;
dgGrid.DataBind();
//Get the HTML for the control.
dgGrid.RenderControl(hw);
//Write the HTML back to the browser.
//Response.ContentType = application/vnd.ms-excel;
Response.ContentType = "application/vnd.ms-excel";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + "");
this.EnableViewState = false;
HttpContext.Current.Response.Write(sw.ToString());
                    HttpContext.Current.Response.Flush();
                    HttpContext.Current.Response.End();
}}try this should help