简体   繁体   English

OpenXML append 行到 Word 中的现有表

[英]OpenXML append rows to an existing table in Word

I want to append rows to an existing table which has the header row only.我想将 append 行添加到仅具有 header 行的现有表中。 I use OpenXML but I cannot open Word document due to error 0x80004005.我使用 OpenXML,但由于错误 0x80004005,我无法打开 Word 文档。 Here is the source I think is OK but...:这是我认为还可以的来源,但是...:

public static byte[] WordDocument(List<List<string>> data)
{
  using (MemoryStream mem = new MemoryStream())
  {
    byte[] byteArray = File.ReadAllBytes(templatePath);
    mem.Write(byteArray, 0, (int)byteArray.Length);
    using (WordprocessingDocument wordDocument = WordprocessingDocument.Open(mem, true))
    {
      Table table = wordDocument.MainDocumentPart.Document.Body.Elements<Table>().First();
      foreach (var line in data)
      {
        TableRow tr = new TableRow();
        foreach (var column in line)
        {
          TableCell tc = new TableCell(new Paragraph(new Run(new Text(column))));
          tr.Append(tc);
        }
        table.Append(new TableRow());
      }
    }
    return mem.ToArray();
  }
}

document.xml: PasteBin document.xml: PasteBin

Rewind the stream after writing to it.写入 stream 后倒带。 Out of interest, why use a stream anyway, rather than just loading from the document directly?出于兴趣,为什么要使用 stream ,而不是直接从文档加载?

Shouldn't that be table.Append(tr);那不应该是table.Append(tr); instead of table.Append(new TableRow());而不是table.Append(new TableRow()); ? ?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM