0

これは非常に素朴な質問になる可能性があります。Excelファイルに書き込みたいのですが、データの挿入が新しい行で行われるたびに。これが私が詳細にしなければならないことです:

  1. Excel を動的に作成し、現在の日付に基づいて名前を付けます。
  2. "Actual"、"Expected"、および Outcome などのヘッダーを追加します。
  3. 上記の列に日付を挿入します。

特定のフィールドを検証する小さなコードがあるため、期待される動作から逸脱するフィールドを Excel に書き込みたいと考えています。したがって、コードがそのExcelに書き込む必要があるエラーを見つけるたびに、それぞれが実行されます。

4

3 に答える 3

2

Excel スプレッドシート XML 形式を使用すると、サードパーティのライブラリを使用せずに Excel ファイルに書き込むことができます。必要なのは、XmlTextWriter を使用することだけです。以下に例を示します (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();
于 2013-05-22T09:23:38.893 に答える