【发布时间】:2014-03-13 11:24:29
【问题描述】:
我能够从 asp:table 生成 excel 文件,但是在打开文件时生成 excel 文件后会发出警告。您尝试打开的文件与文件扩展名指定的格式不同 我已经从这个链接http://www.aspsnippets.com/Articles/Solution-ASPNet-GridView-Export-to-Excel-The-file-you-are-trying-to-open-is-in-a-different-format-than-specified-by-the-file-extension.aspx找到了解决这个警告的方法
所以我使用了 ClosedXML 库,但是在将数据添加到 excel 表时,它只接受可数据、数据集格式,并且我以字符串格式获取数据,因此它正在生成空白的 excel 表。请检查我尝试过的代码。
LoadDetailsToTable();
System.IO.StringWriter sw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new HtmlTextWriter(sw);
tbl_loctbl.RenderControl(hw);
using (XLWorkbook wb = new XLWorkbook())
{
var ws = wb.Worksheets.Add("asd");
ws.Cell(2, 1).InsertTable(sw.ToString());
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
HttpContext.Current.Response.AddHeader("content-disposition", String.Format(@"attachment;filename=newfile.xlsx"));
using (MemoryStream MyMemoryStream = new MemoryStream())
{
wb.SaveAs(MyMemoryStream);
MyMemoryStream.WriteTo(HttpContext.Current.Response.OutputStream);
MyMemoryStream.Close();
}
HttpContext.Current.Response.End();
}
这里LoadDetailsToTable()函数将数据加载到asp表中。tbl_loctbl是表id。
【问题讨论】: