通过C#写入Excel

这可能是一个非常天真的问题。 我想写入一个excel文件,每次插入的数据应该发生在一个新的行。 这是我必须做的细节:

  1. dynamic创buildExcel并根据当前date命名。
  2. 添加头像“实际”,“预期”和结果。
  3. 在上面的列中插入date。

我有一个validation某些领域的小代码,所以我想写一个偏离预期行为的领域。 所以每当我的代码发现错误,它应该写入该Excel中运行。

通过使用Excel Spreadsheet XML格式,可以写入Excel文件而不使用任何第三方库。 所有你需要的是使用XmlTextWriter。 下面是一个例子(假设提供了写excel的stream):

XmlTextWriter 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(); // Creates the worksheet w.WriteStartElement("Worksheet"); w.WriteAttributeString("ss", "Name", null, "Sheet1"); // Creates the table w.WriteStartElement("Table"); // Creates a row. w.WriteStartElement("Row"); // Creates a cell with "SomeData" written in it. w.WriteStartElement("Cell"); w.WriteStartElement("Data"); w.WriteAttributeString("ss", "Type", null, "String"); w.WriteString("SomeData"); w.WriteEndElement(); w.WriteEndElement(); w.WriteEndElement(); // Closes the row. w.WriteEndElement(); w.WriteEndElement(); w.WriteEndElement(); w.WriteEndDocument(); w.Flush(); w.Close(); 

你会想使用封闭的XML这是一个Open XML SDK的包装。 看看他们的例子。

如果您不想依赖第三方库,则可以直接使用Open XML SDK 。

你可以用下面的方法写入excel文件:

  1. 使用Excel应用程序的COM实例
  2. 使用第三方组件编写excel

我使用syncfusion xslIo组件来读取和写入excel文件