0

I have a requirement to add/update TOC - Table of Contents in MS document using OpenXML. I am facing challenges to achieve the same. I am using MS Office 2016.

I have tried all the options from this post: How to generate Table Of Contents using OpenXML SDK 2.0?

Also gone through Eric White videos.

I am trying to use UpdateField option and able to add empty TOC following the sample code from the above link.

However when I open the document I am not getting a pop-up dialog which will ask to update the TOC.

Here is the sample code:

            var sdtBlock = new SdtBlock();
            sdtBlock.InnerXml = GetTOC(); //TOC Xml
            document.MainDocumentPart.Document.Body.AppendChild(sdtBlock);

            DocumentFormat.OpenXml.Wordprocessing.SimpleField f;
            f = new SimpleField();
            f.Instruction = "sdtContent";
            f.Dirty = true;
            document.MainDocumentPart.Document.Body.Append(f);

           
            var setting = document.MainDocumentPart.DocumentSettingsPart;
            if (setting != null)
            {
                document.MainDocumentPart.DocumentSettingsPart.Settings.Append(new UpdateFieldsOnOpen() { Val = new DocumentFormat.OpenXml.OnOffValue(true)});
                document.MainDocumentPart.DocumentSettingsPart.Settings.Save();
            }

enter image description here

It is displaying default message, whereas I have valid entries (Headings).

Is it due to MS Office 2016? UpdateField Pop-up is not coming?

I don't want to go with below options:

  1. Word Automation - Due to Microsoft.Office.Interop.Word
  2. Word Automation Services - Require Sharepoint for this
  3. Adding Macro - As it is asking to save the document every time I open it.

Also let me know if there is any better option to create/update TOC.

Your answer/comment is really very helpful.

Matt
  • 23
  • 1
  • 4
  • I am tempted to take the error message at its face value. It is possible that what you conceive of as a heading is something Word does not see that way. Within Word, what happens if you try to add a TOC usng the interface? Perhaps save a sample document with the problem on DropBox or OneDrive and post a view link here. – Charles Kenyon Feb 12 '21 at 07:51
  • Cross-posted at: https://answers.microsoft.com/en-us/msoffice/forum/all/issue-while-addingupdating-toc-in-ms-word-using/c20532c0-be3f-4263-b0dd-18d9a1a7c664/. For cross-posting etiquette, please read: http://www.excelguru.ca/content.php?184 – macropod Feb 12 '21 at 08:28

0 Answers0