Search code examples
ms-wordopenxmlopenxml-sdk

Word cannot open DOCX file with a table


I am trying to run mail merge against a DOCX file using Open XML API - just replacing a <w:t> element with a table (see below). Even the simplest table created using the following code results in Word erroring out when opening the file.

If I get rid of the row (so that I only have <w:tbl> / <w:tblGrid> / <w:GridCol>). there is no error, but then I cannot have any data of course.

Can anybody see what I am doing wrong?

Table table = new Table(new TableGrid(new GridColumn() { Width = "2000"}),
                        new TableRow(new TableCell(new Paragraph(new Run(new Text("test")))))
                                      );
TextNode.Parent.ReplaceChild<Text>(table, TextNode);

enter image description here

enter image description here


Solution

  • You cannot replace <w:t> with <w:tbl>. The table is a block-level element so you can place it in the same places where you have the paragraph (<w:p>).

    In other words, you can place it as a child element of one of the following: body, comment, customXml, docPartBody, endnote, footnote, ftr, hdr, sdtContent, tc, and txbxContent.

    So, try something like this:

    // TextNode (Text) -> Parent (Run) -> Parent (Paragraph)
    var paragraph = TextNode.Parent.Parent as Paragraph;
    paragraph.Parent.ReplaceChild(table, paragraph);
    

    EDIT:

    If the parent element is <w:tc>, you should add an empty paragraph to its end:

    // TextNode (Text) -> Parent (Run) -> Parent (Paragraph)
    var paragraph = TextNode.Parent.Parent as Paragraph;
    
    var parent = paragraph.Parent;
    parent.ReplaceChild(table, paragraph);
    
    if (parent is TableCell)
        parent.InsertAfter(new Paragraph(), table);