【发布时间】:2013-11-15 14:16:13
【问题描述】:
我以编程方式使用 xml 生成 excel 文件。然后尝试打开文件时,我收到以下消息:
“您尝试打开的文件 'MyFile.xls' 的格式与文件扩展名指定的格式不同。在打开文件之前,请确认文件没有损坏并且来自受信任的来源。您是否现在要打开文件吗?”
当用户按下“是”时,文件打开没有问题。但是这个警告和需要额外点击是很烦人的。您能否建议我如何摆脱它?
这是我的代码的一部分:
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();
【问题讨论】:
-
你试过
.xlsx吗? -
您需要 xls 或 xlsx 文件吗?
-
是的。在此我收到另一条消息:“Excel 无法打开文件 'MyFile.xlsx',因为文件格式或文件扩展名无效。”并且文件没有打开。
-
@Shymep 我需要这些中的任何一个,只是没有那个警告。
-
“当用户按下“是”时,文件会毫无问题地打开。” - 这是因为 Excel 尽力显示您输入的内容。这并不意味着它是一个有效的 Excel 文件,而这正是您的问题:您只是在编写一些 类似于 Excel 文档的标签,但它并没有确认符合规范。使用 Excel 库,它们就是为此而构建的。