如何以编程方式在word文件中创建索引?

How to create an index in word file programmatically?

假设有 table 个数据项,我们需要为其中的任何一项创建索引。 那么,如何以编程方式在 Docx 文件中创建索引,即在 docx4j 的帮助下。

 MainDocumentPart mdp = word.getMainDocumentPart();
        String textXpath = "//w:t";
        List<Object> textNodes= mdp.getJAXBNodesViaXPath(textXpath, true);
        c=0;
        for (Object obj : textNodes)
        {
            Text text = (Text) ((JAXBElement<?>) obj).getValue();       
            textValue = text.getValue();
         String[] words = textValue.split("\W+");
            for (String word : words) 
            {
             word = word.toLowerCase();
             List<Integer> list = occurences.get(word);

             if (list == null) 
             {
                 list = new ArrayList<Integer>();
                 occurences.put(word, list);
             }

             list.add(c);
         }

         c++;

        }
        //System.out.print(occurences.toString());
        word.getMainDocumentPart().addParagraphOfText("");
        word.getMainDocumentPart().addParagraphOfText("");
        word.getMainDocumentPart().addStyledParagraphOfText("Title", "INDEX");
        String count = occurences.toString();
        word.getMainDocumentPart().addParagraphOfText("count");