Search code examples
c#ms-wordopenxmlopenxml-sdk

OpenXML inserts annoying carriage return at top of document or before table


I'm inserting a table to a word document where the document contains nothing except for a header:

using (var doc = WordprocessingDocument.Open(targetfile, true))
{
    var body = doc.MainDocumentPart.Document.Body;
    var table = new Table();

    foreach (var package in consignment.Packages)
    {
        // Build the table rows here
    }

    doc.MainDocumentPart.Document.Append(table);
    doc.MainDocumentPart.Document.Save();
    doc.Save();
}

Its working well, but when I open the document I can see there is a carriage return at the beginning of the document, so I have to delete that to remove the space:

enter image description here

The annoying space is highlighted in yellow, with the bottom of the header above and my table below.

How can I get OpenXML to not do this? I.e. insert the table right at the top of the document, not after a carriage return

Note that the carriage return is not there in the template docx


Solution

  • The reason the table is not at the top of the document is because: 1) a document always contains, at a minimum, one paragraph and 2) the table is being appended to the document (meaning "at the end").

    Instead, insert the table before the first paragraph, something like this:

    var body = doc.MainDocumentPart.Document.Body;
    var table = new Table();
    
    foreach (var package in consignment.Packages)
    {
        // Build the table rows here
    }
    Paragraph firstPara = doc.Body.Descendants<Paragraph>().First();
    body.InsertBefore(table, firstPara);
    

    Note that there will be a paragraph mark following the table - this is required by Word in order to store information about the table. (Mainly, it's location on the page.)