Search code examples
c#openxmlwordprocessingml

Insert a table into a middle of word processing document (Open XML SDK)


I have a template Word document which i fill details into with openXML SDK 2.0 (using c#). I also need to insert a table into file, and i found this tutorial on MSDN. But - the example is appending the table to the end of the document, and I want it to be somewhere in the middle. I may need to replace this line:

doc.MainDocumentPart.Document.Body.Append(table);

with something else. (The full code is in the link above).

Please help me.. I found nothing yet.

Thanks.


Solution

  • One way to do this may be to use Content Controls as placeholders to insert the table into them from code.

    var myContentControl = doc.MainDocumentPart.Document.Body.Descendants<SdtBlock>()
        .Where(e => e.Descendants<SdtAlias>().FirstOrDefault().Val == "myTablePlaceholder").FirstOrDefault();
    
    SdtContentBlock sdtContentBlock1 = new SdtContentBlock();
    sdtContentBlock1.Append(table); // Your table
    myContentControl.Append(sdtContentBlock1);