I need to format the table of contents (TOC) in multiple Word documents daily. I'm using Power Automate with OpenXML (C#) to add the TOC. However, the code is inserting a TOC but not update it automatically, as shown in the attached image.
The main requirement is:
If a TOC already exists, it should be updated.
If no TOC is present, it should be inserted.
Note: The solution must work online only.
Is there any other approach to achieve this?
private static void GenerateTableOfContents(Body body)
{
var tocParagraph = new Paragraph(new Run(new Text("Table of Contents")));
tocParagraph.ParagraphProperties = new ParagraphProperties(new Justification() { Val = JustificationValues.Center });
var tocFieldStart = new Run(new FieldChar() { FieldCharType = FieldCharValues.Begin });
var tocFieldCode = new Run(new FieldCode("TOC \\o \"1-3\" \\h \\z \\u") { Space = SpaceProcessingModeValues.Preserve });
var tocFieldSeparator = new Run(new FieldChar() { FieldCharType = FieldCharValues.Separate });
var tocFieldEnd = new Run(new FieldChar() { FieldCharType = FieldCharValues.End });
var tocContent = new Paragraph(tocFieldStart, tocFieldCode, tocFieldSeparator, tocFieldEnd);
body.InsertAt(tocParagraph, 0);
body.InsertAt(tocContent, 1);
ForceUpdateFields(body);
}
private static void ForceUpdateFields(Body body)
{
var mainPart = body.Ancestors<Document>().First().MainDocumentPart;
var settingsPart = mainPart.DocumentSettingsPart ?? mainPart.AddNewPart<DocumentSettingsPart>();
if (settingsPart.Settings == null)
settingsPart.Settings = new DocumentFormat.OpenXml.Wordprocessing.Settings();
settingsPart.Settings.Append(new UpdateFieldsOnOpen() { Val = true });
}
Thanks, Renjeesh
for reference cick here