有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

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

我现在尝试在文档的开头添加一个表,该表有三列(第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) 个答案

  1. # 1 楼答案

    我想出来了:

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