简体   繁体   中英

OpenXML append rows to an existing table in Word

I want to append rows to an existing table which has the header row only. I use OpenXML but I cannot open Word document due to error 0x80004005. 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

Rewind the stream after writing to it. Out of interest, why use a stream anyway, rather than just loading from the document directly?

Shouldn't that be table.Append(tr); instead of table.Append(new TableRow()); ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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