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

我以编程方式使用xml生成excel文件。 在尝试打开文件时,收到以下消息:

“您试图打开的文件”MyFile.xls“采用与文件扩展名指定的格式不同的格式。在打开文件之前,确认文件没有被破坏,并且来自可靠来源。现在的文件?“

当用户按“是”时,文件打开没有问题。 但是这个警告和需要额外点击是烦人的。 你能build议我怎么能摆脱它?

这是我的代码的一部分:

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来创build电子表格,使用专门编写来创buildexcel文件的库可能会有更好的运气。 否则,你将最终遇到类似你所看到的问题 – xmlns属性会导致文件出现损坏。 专门为创buildxls文件而编写的库已经解决了这个问题。

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

在使用XmlTextWriter您会得到与.xls不同的格式。 你创build的是,它是由Excel支持,但每次你会收到一个警告消息。
正如@matt已经提到的那样,使用特定的库以适当的excel格式创build文件要容易得多。 我也build议看一下npoi库。 如果使用旧的.xls格式,这是相当不错的。