Search code examples
javaapache-poidocx4j

How to create or update table of contents in a word file?


I can read or write word document in Java using Apache POI or docx4j. But I cant find any references to create or update table of contents in a Word file. Is there any other API can support TOC in Java? Or, is it possible in Apache POI or docx4j to have options to create or update TOC?


Solution

  • To create table of contents with apache poi you can just use:

    doc.createTOC();
    

    But it seems a bit buggy. The TOC is created but the (MS Office pro 2010) does not seem to recognize it as TOC and the references are not working.

    Or you can call:

    doc.enforceUpdateFields();
    

    This will create a popup in word document with: "This document contains fields that may refer to other files. Do you want to update the fields in this document?", which looks a bit dodgy if you are opening a new doc :)