如何在Apache POI Word中创建超链接?

时间:2018-03-09 11:12:16

标签: java apache-poi

如何使用apache-poi在Word文档中创建超链接?是否可以使用相对路径?

2 个答案:

答案 0 :(得分:3)

直到现在(2018年3月,apache poi版本3.17),有XWPFHyperlinkRun但不是创建此类广告的方法。所以我们需要使用底层的低级方法。

以下示例提供了在XWPFHyperlinkRun中创建XWPFParagraph的方法。之后,XWPFHyperlinkRun可以作为XWPFRun处理,以便进一步格式化,因为它扩展了这个类。

import java.io.*;

import org.apache.poi.xwpf.usermodel.*;

import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTHyperlink;

public class CreateWordXSSFHyperlinkRun {

 static XWPFHyperlinkRun createHyperlinkRun(XWPFParagraph paragraph, String uri) {
  String rId = paragraph.getDocument().getPackagePart().addExternalRelationship(
    uri, 
    XWPFRelation.HYPERLINK.getRelation()
   ).getId();

  CTHyperlink cthyperLink=paragraph.getCTP().addNewHyperlink();
  cthyperLink.setId(rId);
  cthyperLink.addNewR();

  return new XWPFHyperlinkRun(
    cthyperLink,
    cthyperLink.getRArray(0),
    paragraph
   );
 }

 public static void main(String[] args) throws Exception {

  XWPFDocument document = new XWPFDocument();

  XWPFParagraph paragraph = document.createParagraph();
  XWPFRun run = paragraph.createRun();
  run.setText("This is a text paragraph having ");

  XWPFHyperlinkRun hyperlinkrun = createHyperlinkRun(paragraph, "https://www.google.de");
  hyperlinkrun.setText("a link to Google");
  hyperlinkrun.setColor("0000FF");
  hyperlinkrun.setUnderline(UnderlinePatterns.SINGLE);

  run = paragraph.createRun();
  run.setText(" in it.");

  paragraph = document.createParagraph();

  paragraph = document.createParagraph();
  run = paragraph.createRun();
  run.setText("This is a text paragraph having ");

  hyperlinkrun = createHyperlinkRun(paragraph, "./test.pdf"); //path in URI is relative to the Word document file
  hyperlinkrun.setText("a link to a file");
  hyperlinkrun.setColor("0000FF");
  hyperlinkrun.setUnderline(UnderlinePatterns.SINGLE);
  hyperlinkrun.setBold(true);
  hyperlinkrun.setFontSize(20);

  run = paragraph.createRun();
  run.setText(" in it.");

  document.write(new FileOutputStream("CreateWordXSSFHyperlinkRun.docx"));
  document.close();

 }
}

答案 1 :(得分:0)

2021 年更新

从 POI 4.1.1 开始,可以使用它的方法将超链接添加到段落中。

XWPFDocument docx = new XWPFDocument();
XWPFParagraph paragraph = docx.createParagraph();
run = paragraph.createHyperlinkRun("https://stackoverflow.com/");
run.setText("Stack Overflow");
run.setUnderline(UnderlinePatterns.SINGLE);
run.setColor("0000FF");