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

Dav*_*het 5 c# excel

我以编程方式使用 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();
Run Code Online (Sandbox Code Playgroud)

mat*_*att 2

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

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