1. 遍历word document对象中的段落信息找到目录所在段落,设置其中值为空字符串,取消其目录属性。如果找不到则无目录信息。
/**
* 获取目录段落信息
*
* @param document word对象
* @return 目录段落
*/
private XWPFParagraph getTocParagraph(XWPFDocument document) {
List<XWPFParagraph> paragraphs = document.getParagraphs();
for (XWPFParagraph paragraph : paragraphs) {
List<XWPFRun> runs = paragraph.getRuns();
if (CollectionUtils.isNotEmpty(runs)) {
for (XWPFRun run : runs) {
CTText[] instrTextArray = run.getCTR().getInstrTextArray();
for (CTText ctText : instrTextArray) {
if (ctText.getStringValue().trim().startsWith("TOC \\o \"1-2")) {
ctText.setStringValue("");
return paragraph;
}
}
}
}
}
return null;
}
2. 刷新目录信息:
2.1 强制刷新目录 低版本的office无法打开word 文档
document.enforceUpdateFields();
2.2 在word中指定位置生成新的目录信息
// 更新目录
XWPFParagraph tocParagraph = getTocParagraph(document);
if (tocParagraph == null){
document.enforceUpdateFields();
}else {
XmlCursor xmlCursor = tocParagraph.getCTP().newCursor();
// 重新生成目录
XWPFParagraph newTocParagraph = document.insertNewParagraph(xmlCursor);
CTSimpleField ctSimpleField = newTocParagraph.getCTP().addNewFldSimple();
ctSimpleField.setInstr("TOC \\o \"1-2\"");
ctSimpleField.setDirty(true);
}