如何将数据表导出到Excel [英] How to export Data table to excel
问题描述
嗨专家,
我有一个要求,我需要将数据表导出到excel
并且必须保存项目文件夹中的excel文件。
我试过这个示例代码但它不能正常工作
Hi experts,
I have got a requirement that, there I need to export data table to excel
and have to save that excel file in project folder.
I have tried with this sample code but its not working
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();
//获取控件的HTML。
dgGrid.RenderControl(hw);
//将HTML写回浏览器。
//Response.ContentType = application / vnd.ms-excel;
Response.ContentType =application / vnd。 ms-excel;
Response.AppendHeader(Content-Disposition,附件; filename =+ filename +);
this.EnableViewState = false;
Response.Write(tw.ToString());
Response.End();
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();
任何人都可以帮我解决这个问题???
谢谢
Keerthi Kumar
can any one please help me to solve this issue???
thanks
Keerthi Kumar
推荐答案
按以下方式执行
Do it in following way
public void ExportToExcel(DataTable dt)
{
if (dt.Rows.Count > 0)
{
string filename = "Filename.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();
dgGrid.RenderControl(hw);
Response.ContentType = "application/vnd.ms-excel";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + "");
this.EnableViewState = false;
Response.Write(tw.ToString());
Response.End();
}
}
我刚刚删除了try catch block以获取相同的已发布代码,现在正常工作
I just Removed try catch block for the same posted code its working fine now
这篇关于如何将数据表导出到Excel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!