将文档中章节的超链接插入 XWPFTable 中的单元格

Insert hyperlinks to chapters in document to cells in a XWPFTable

我的程序创建了一个包含许多章节和子章节的 word 文件。

我现在尝试在文档的开头添加一个 table 三列(第 1 列:章节列表,第 2 列:子章节列表和第 3 列:留空,它将是由用户填写摘要),在前两列中,我希望文本是指向相应 chapter/subchapter 的超链接。

我添加了 table,但超链接有问题。我找到了一些关于如何插入内部超链接的代码。但是超链接是直接插入到chapter/subchapter之后的。我希望单元格中的文本成为超链接:

private static void addHyperlink(XWPFParagraph para, String text, String bookmark) {
    // Create hyperlink in paragraph
    CTHyperlink cLink = para.getCTP().addNewHyperlink();
    cLink.setAnchor(bookmark);
    // Create the linked text
    CTText ctText = CTText.Factory.newInstance();
    ctText.setStringValue(text);
    CTR ctr = CTR.Factory.newInstance();
    ctr.setTArray(new CTText[] { ctText });

    // Insert the linked text into the link
    cLink.setRArray(new CTR[] { ctr });
}

private static void writeParagraphToDocument(String chapterName, String subchapterName) {
    XWPFParagraph chapterParagraph = resultDocument.createParagraph();
    chapterParagraph.setStyle(heading1Style);
    XWPFParagraph subchapterParagraph = resultDocument.createParagraph();
    subchapterParagraph.setStyle(heading2Style);

    // code to add paragraph in document

    XWPFTableRow l_tableRow = m_summaryTable.createRow();
    l_tableRow.getCell(0).setText(chapterName);
    l_tableRow.getCell(1).setText(subchapterName);
    addHyperlink(chapterParagraph, chapterName, "nameOfParagraph");
    l_tableRow.getCell(2).setText("");
}

我想通了:

private static void addHyperlink(XWPFParagraph p_paragraphCell, XWPFParagraph p_paragraphLink, String p_linkedText, String p_paragraphText) {
    // Create hyperlink in paragraph
    CTHyperlink cLink = p_paragraphLink.getCTP().addNewHyperlink();
    cLink.setAnchor(p_paragraphText);
    // Create the linked text
    CTText ctText = CTText.Factory.newInstance();
    ctText.setStringValue(p_linkedText);
    CTR ctr = CTR.Factory.newInstance();
    ctr.setTArray(new CTText[] { ctText });

    // Insert the linked text into the link
    cLink.setRArray(new CTR[] { ctr });

    p_paragraphCell.getCTP().setHyperlinkArray(new CTHyperlink[] { cLink });
    p_paragraphLink.getCTP().removeHyperlink(0);
}