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

 ̄綄美尐妖づ 提交于 2019-12-23 22:21:46

问题


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



来源:https://stackoverflow.com/questions/24861645/how-to-create-or-update-table-of-contents-in-a-word-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!