gpt4 book ai didi

c# - 如何避免在打开以编程方式生成的 Excel 文件时出现警告

转载 作者:行者123 更新时间:2023-11-30 12:09:52 25 4
gpt4 key购买 nike

我以编程方式使用 XML 生成 Excel 文件。然后尝试打开文件时,我收到以下消息:

“您尝试打开的文件“MyFile.xls”的格式与文件扩展名指定的格式不同。打开文件前请确认文件未损坏且来源可靠。您是否要现在打开文件吗?”

当用户按下"is"时,文件打开没有问题。但是这个警告和需要额外点击是很烦人的。我怎样才能摆脱它?

这是我的代码的一部分:

        var stream = File.Create(path);
var w = new XmlTextWriter(stream, null); // Creates the XML writer from pre-declared stream.

//First Write the Excel Header
w.WriteStartDocument();
w.WriteProcessingInstruction("mso-application", "progid='Excel.Sheet'");

w.WriteStartElement("Workbook");
w.WriteAttributeString("xmlns", "urn:schemas-microsoft-com:office:spreadsheet");
w.WriteAttributeString("xmlns", "o", null, "urn:schemas-microsoft-com:office:office");
w.WriteAttributeString("xmlns", "x", null, "urn:schemas-microsoft-com:office:excel");
w.WriteAttributeString("xmlns", "ss", null, "urn:schemas-microsoft-com:office:spreadsheet");
w.WriteAttributeString("xmlns", "html", null, "http://www.w3.org/TR/REC-html40");

w.WriteStartElement("DocumentProperties");
w.WriteAttributeString("xmlns", "urn:schemas-microsoft-com:office:office");
w.WriteEndElement();

// Creates the workbook
w.WriteStartElement("ExcelWorkbook");
w.WriteAttributeString("xmlns", "urn:schemas-microsoft-com:office:excel");
w.WriteEndElement();

最佳答案

与其使用 XmlTextWriter 来创建电子表格,不如使用专门为创建 excel 文件而编写的库来获得更好的运气。否则,您最终会遇到与您所看到的类似的问题 - 诸如 xmlns 属性之类的小错误会导致您的文件看起来已损坏。专门为创建 xls 文件而编写的库应该已经解决了这个问题。

EPPlus 似乎得到了很好的支持:http://epplus.codeplex.com/

关于c# - 如何避免在打开以编程方式生成的 Excel 文件时出现警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20003086/

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