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))));
        table.Append(new TableRow());
    return mem.ToArray();

document.xml: PasteBin

asked on Stack Overflow Oct 4, 2019 by Sándor Hatvani • edited Oct 4, 2019 by Sándor Hatvani

1 Answer


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

answered on Stack Overflow Oct 4, 2019 by Aaron Queenan

User contributions licensed under CC BY-SA 3.0