【发布时间】:2018-02-27 07:41:17
【问题描述】:
我正在尝试以 excel 格式下载我的数据。以下代码完美地完成了工作,但格式被破坏了。
我得到的错误 - 文件格式和扩展名不匹配。该文件可能已损坏或不安全。除非你相信它的来源,否则不要打开它。你还是要打开它吗? 确认是,文件打开。
请查看代码并帮助我了解必须进行哪些更改才能将数据下载到(xls 97-2003 excel 工作簿)中。
if (dt4.Rows.Count > 0)
{
string filename = "DownloadMobileNoExcel.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 = dt4;
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());
【问题讨论】:
-
尝试添加“Content-Type”、“application/Excel”
-
刚刚试过。它也没有帮助。
-
开始使用专门的库来创建 Excel 文件,例如 EPPlus。您现在所做的只是创建一个扩展名为 .xls 的 HTML 页面。
-
dgGrid.RenderControl(hw);是做什么的?