How to create or update table of contents in a wor

2019-07-16 03:41发布

问题:

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?

回答1:

There's a cleaner way for this too. You just need to open a empty docx which will act as a template. Add some sample text into it with the style that you want to include and then this piece of code will work.

XWPFDocument document = new XWPFDocument(new FileInputStream("template.docx");
paragraph = document.createParagraph();
lastParagraph.setStyle("Heading1"); 


回答2:

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 :)