Thanks to Dmitry Pavlov (@DmitryPavlov) for help.
I do not want to answer my question, but it just illustrates the steps that I have taken.
A tip for anyone interested is to look at the 5-part screen written by Eric White - Exploring Content Tables in Open XML WordprocessingML Documents . It has all the information regarding adding and updating TOC (much more).
My solution was to use a template (just a plain empty document with styles for everything I need: heading 1-5, TOC style, etc.). This is especially useful as a quick fix for the styles problem (a new document with TOC will have a new style.xml created, there is some additional data in this file, as a result of which the hierarchy in TOC is not expected - i.e. heading 2 is a child of heading 1 , heading 3 is a child of heading 2, etc.).
Thus:
Create a Word document and add all the elements that you expect to add later programmatically (for example, heading 1-5, table of contents, etc.). Delete all contents and save the document (the reason for this is to create styles for all the necessary elements).
I personally added a template (the file created in step 1) as a resource in my project.
In your code, create a new copy of the template (this will be the actual file you will be working on). I used:
byte[] stream = Properties.Resources.Template; File.WriteAllBytes(@"D:\Template.docx", stream); File.Copy(@"D:\Template.docx", @"D:\New.docx");
Reset all data to this document.
Add the source files from screen 2, 3 or 4 to your project (for this, see screenshot 3). At the end of these posts you will find a link to download TocAdder.zip. Or just add the link to TocAdder.dll.
Insert TOC. Example:
using (WordprocessingDocument wdoc = WordprocessingDocument.Open(@"D:\New.docx", true)) { XElement firstPara = wdoc .MainDocumentPart .GetXDocument() .Descendants(Wp) .FirstOrDefault(); TocAdder.AddToc(wdoc, firstPara, @"TOC \o '1-3' \h \z \u", null, null); }
Replace the styles in the newly created document with those in the template. You can use this resource from MSDN: Replacing parts of styles in Word 2010 documents using the Open XML SDK 2.0 . Again, an example:
string fromDoc = @"D:\Template.docx"; string toDoc = @"D:\New.docx"; var node = WDExtractStyles(fromDoc, false); if (node != null) WDReplaceStyles(toDoc, node, false); node = WDExtractStyles(fromDoc); if (node != null) WDReplaceStyles(toDoc, node);
If necessary, use one of the methods described in 3 or 4 pages of the screen to get around the problem with the modal dialog box that Word puts.
Hope this will be helpful to someone.
Yeseanul
source share