【问题标题】:How to avoid warning on opening a programmatically generated Excel file如何避免在打开以编程方式生成的 Excel 文件时出现警告
【发布时间】: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 库,它们就是为此而构建的。

标签: c# excel


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    当您使用XmlTextWriter 时,您会得到与.xls 不同的格式。您创建的内容,是的,它受 Excel 支持,但每次您都会收到一条警告消息。
    正如@matt 已经提到的,使用特定的库以适当的 excel 格式创建文件要容易得多。我还建议查看npoi 库。如果您使用旧的.xls 格式,那就太好了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-08-01
      • 2010-11-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多