通过c#写入Excel

本文关键字:Excel 写入 通过 | 更新日期: 2023-09-27 18:15:00

这可能是一个非常幼稚的问题。我想写入到一个excel文件,每次插入的数据应该发生在一个新的行。下面是我要做的细节:

  1. 动态创建Excel,并根据当前日期。
  2. 添加"实际"、"预期"answers"结果"等标题。
  3. 在以上列中插入日期。

我有一个小的代码来验证某些字段,所以我想把偏离预期行为的字段写进excel。因此,每次运行时,只要我的代码发现一个错误,它应该写入excel。

通过c#写入Excel

使用excel电子表格XML格式可以在不使用任何第三方库的情况下写入excel文件。您所需要的只是使用xmltextwwriter。下面是一个示例(假设提供了编写excel的流):

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();

您可能希望使用Closed XML,它是Open XML SDK的包装。看看他们的例子。

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

您可以使用以下方法写入excel文件:

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

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