gpt4 book ai didi

c# - 转换 asp :Table to excel format

转载 作者:行者123 更新时间:2023-11-28 03:24:04 26 4
gpt4 key购买 nike

我能够从 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。

最佳答案

很遗憾,您使用的两个标记不兼容。支持 Excel 中的 HTML 表格标记,但它不支持您的图书馆期望输出的 OpenXML。

在后台,Excel 需要有效的 XML 文件格式; html 虽然受到松散支持,但不是原生 xlsx 格式。

互联网上有一些库可以将 html 转换为 openxml,但是这可以通过迭代数据集并使用 OpenXML SDK 实际添加单元格和行来解决。

关于c# - 转换 asp :Table to excel format,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22377104/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com