Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 492
Ramakrishna Avatar asked Oct 23 '25 18:10

Ramakrishna


2 Answers

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

like image 176
Patrik Bego Avatar answered Oct 26 '25 08:10

Patrik Bego


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"); 
like image 45
Seema Avatar answered Oct 26 '25 06:10

Seema



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!