不废话,直接放代码吧。
public class AddTOC {
public static void main(String[] args) throws IOException, InvalidFormatException {
FileInputStream fileInputStream = new FileInputStream("xxxx");
XWPFDocument doc = new XWPFDocument(fileInputStream);
generateTOC(doc);
OutputStream out = new FileOutputStream("xxxx");
doc.write(out);
out.close();
}
public static void generateTOC(XWPFDocument document) throws InvalidFormatException, FileNotFoundException, IOException {
String findText = "toc";
String replaceText = "";
for (XWPFParagraph p : document.getParagraphs()) {
for (XWPFRun r : p.getRuns()) {
int pos = r.getTextPosition();
String text = r.getText(pos);
System.out.println(text);
if (text != null && text.contains(findText)) {
text = text

这篇博客介绍了如何使用Java的POI库来添加Word文档的目录。关键步骤包括在Word文档中预留位置,并用特定字符串(如'toc')作为标记。运行代码后,需要在打开的文档中确认操作以生成目录。然而,存在一个问题,即打开文档时可能会出现域引用警告,并且目录生成的成功与否依赖于用于定位的字符串是否被正确识别。建议使用较短且不太可能出现的字符串作为标记,以提高目录生成的可靠性。
&spm=1001.2101.3001.5002&articleId=100612241&d=1&t=3&u=b3d6dc3247ee47c3a78326a2f2ff7cb1)
4592

被折叠的 条评论
为什么被折叠?



