Java使用POI添加Word文档的目录(Table of contents)

    不废话,直接放代码吧。

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.replace(findText, replaceText);
                    r.setText(text, 0);
                    addField(p, "TOC \\o \"1-3\" \\h \\z \\u");
//                    addField(p, "TOC \\h");
                    break;
                }
            }
        }
    }

    private static void addField(XWPFParagraph paragraph, String fieldName) {
        CTSimpleField ctSimpleField = paragraph.getCTP().addNewFldSimple();
        ctSimpleField.setInstr(fieldName);
        ctSimpleField.setDirty(STOnOff.TRUE);
        ctSimpleField.addNewR().addNewT().setStringValue("<>");
    }
}

生成目录的关键代码是:

CTSimpleField ctSimpleField = paragraph.getCTP().addNewFldSimple();
ctSimpleField.setInstr(fieldName);
ctSimpleField.setDirty(STOnOff.TRUE);

用法:

1、先在word文档中找一页用来展示要生成的目录。并添加一个字符串以便将生成目录替换到这个字符串的位置。(这里我用字母toc当做这个字符串,字符串的名字大家随意)

Java使用POI添加Word文档的目录(Table of contents)_第1张图片

2、代码run起来~~~~~~~

3、打开生成的word文档,会看到一个提示,大概这样:

Java使用POI添加Word文档的目录(Table of contents)_第2张图片

此处必须点

4、好了,开始见证奇迹吧~~

 

现存问题:
1、打开生成的word文档时会弹出“该文档包含的域可能引用了其他文件·····”这个窗口,且必须选择

2、生成的word有时会成功生成目录,有时会失败,且用来当做定位标记的字符串(如上面的toc)会展示出来。原因是:

int pos = r.getTextPosition();
String text = r.getText(pos);

获取的text的值可能不是预期字符串。例如将用来当做定位标记的字符串写为toc1,在代码执行的时候,可能会出现这种情况:
Java使用POI添加Word文档的目录(Table of contents)_第3张图片

toc1被拆分开了,成了toc和1,那下面代码的也就不会执行了,所以生成目录会失败。建议将这个用来当做定位标记的字符串尽量写短一些,比如是一个word文档中前文里不可能出现的1个字母或文字。

 

好了,主要就是这些吧····

转载于:https://my.oschina.net/u/3410302/blog/3048367

你可能感兴趣的:(java)