Search code examples
c#ms-wordopenxmltableofcontents

How To Update Table of Contents of a Word Document Using OpenXML in C#


I am creating Word documents using my OpenXML library in my .net core 6.1 application. Everything is perfect and working smoothly. But after doing everything, I need to update table of contents but I coulnd't find a working solution for that problem.

Is there any method that can be used for OpenXML library like right-clicking table of contents in a Word document and then clincking "Update Field". Updating table of content in Word docements still works but it's not the expecteed ouput for my product. I want to update table of content before document.close() row in the code below.

My code example is as below:

using (var document = WordprocessingDocument.Open(memoryStream, true))
{
    document.ChangeDocumentType(WordprocessingDocumentType.Document);
    body = document.MainDocumentPart.Document.Body;

    //setting word cover
    //setting nodes;
    //setting business lists and insterting them to Word document;

    document.Close();
}

Solution

  • I tried everything months ago to update the table of contents, and the best solution I got from several pages was to put a code that updates ALL the table of contents and references (page numbers too).

    The code is this: Document is the variable where your WordprocessingDocument is saved. rename it as you want/need.

    DocumentSettingsPart settingsPart = Document.MainDocumentPart.GetPartsOfType<DocumentSettingsPart>().FirstOrDefault(); // FirstOrDefault because First gave error "Sequence contains no elements
    if (settingsPart != null) // if null, the document does not have ANY references to update and would give error if tried
    {
        // Create object to update fields on open
        UpdateFieldsOnOpen updateFields = new UpdateFieldsOnOpen
        {
            Val = new DocumentFormat.OpenXml.OnOffValue(true)
        };
        // Insert object into settings part.
        settingsPart.Settings.PrependChild<UpdateFieldsOnOpen>(updateFields);
        settingsPart.Settings.Save();
    }
    
    

    And with this code what you get is that the next time you open the document, that opens a small window that warns that the document is not updated and asks if you want to update it. If you select yes, it will update all. It is the best solution that I got at the time, if someone has a better one I will be pending in this post.

    I hope it helps you.