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

时间:2017-06-12 12:40:34

标签: java hyperlink xwpf

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

我现在正在尝试在文档的开头添加一个包含三列的表(第1列:章节列表,第2列:子章节列表和第3列:保持为空,它将由用户填写摘要)在前两列中,我希望文本成为相应章节/子章节的超链接。

我添加了表格,但我遇到了超链接问题。我找到了一些关于如何插入内部超链接的代码。但是超链接是在章节/子章节之后直接插入的。我希望单元格中的文本是超链接:

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("");
}

1 个答案:

答案 0 :(得分:0)

我明白了:

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);
}