How to generate Table Of Contents using OpenXML SDK 2.0?

Yeseanul picture Yeseanul · Mar 18, 2012 · Viewed 16.2k times · Source

Using the SDK I'm building Word documents that contain reports. These documents need to have TOC. Does anybody have a complete solution that I can follow in order to understand how to do this?

(I've read everything on http://openxmldeveloper.org/)

Answer

Dmitry Pavlov picture Dmitry Pavlov · Mar 19, 2012

Have a look at Fourth and Final Screen-Cast in Series on Adding/Updating the TOC in OpenXML WordprocessingML Documents by Eric White.

Hope that helps!

UPDATE:


According FAQ from MSDN Forums I see that this feature is not supported:

8) How to generate TOC (table of contents) in Word document?

Open XML SDK 2.0 does not have this feature supported. But you can generate a small TOC through Word app, and reflect the TOC parts with Document Reflector component in Open XML SDK Productivity Tool to see how to generate a TOC programmatically. For more detailed information, please refer to:


UPDATE 2


Based on our comments below I could propose to use this scenario:

  1. You manually create an empty DOCX file and insert TOC inside it.
  2. Then you save this file and open it in OpenXML SDK 2.0 Tool, which provides you with the C# code to generate such empty file with TOC placeholder inside.
  3. Then you programmatically flush all the data you need to this DOCX file and save it.
  4. In addition you will need provide the mechanism that will auto update TOC once the data are flushed (or once the document is opened). There are a few options to do that - see screen-casts 3-5 fromthe link to Eric White post I provided above. Especially, I think youshould pay your attention to 5th one - "Shows how to use an AutoOpen macro to update the TOC whenever any document that contains a TOC is opened".

All of that look a bit tricky, but I hope that helps.