【问题标题】:Insert hyperlinks to chapters in document to cells in a XWPFTable将文档中章节的超链接插入到 XWPFTable 中的单元格
【发布时间】:2018-01-09 19:34:07
【问题描述】:

我的程序创建了一个包含许多章节和子章节的 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("");
}

【问题讨论】:

    标签: java hyperlink xwpf


    【解决方案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);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-12
      • 2014-11-20
      • 2018-03-10
      • 1970-01-01
      • 2018-06-13
      • 2011-02-15
      相关资源
      最近更新 更多