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

标签 c# excel

我以编程方式使用 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/

相关文章:

excel - 使用 Excel 仅将唯一列转置为标题行

vba - Excel VBA : How To Remove Duplicate Values From Table?

c# - PresentationFramework.dll 中出现类型为 'System.Windows.Markup.XamlParseException' 的未处理异常

javascript - 在 Angular/.NET MVC 中发出发布请求后如何使用模型进行重定向?

excel - 在 Excel 中串联 1000 多个单元格以识别重复项

vba - 如何为下一个子例程保留该变量的值?

python - 从字符串中删除十六进制表示 - Python

c# - c# 中的(签名的)位图比较

c# - 为什么我在调用 DllImport 之前中断时会得到 AccessViolationException?

c# - 为什么 ICollection 不包含 Add 方法?