如何在XWPFDocument中创建外部链接或电子邮件链接?有一个Excel (HSSF XSSF)的描述,但我没有找到任何类似的Word(HWPF XWPF)。
答案 0 :(得分:9)
public void example() throws Exception{
XWPFDocument document = new XWPFDocument();
//Append a link to
appendExternalHyperlink("https://poi.apache.org", " Link to POI", document.createParagraph());
document.write(new FileOutputStream("resultat.docx"));
}
/**
* Appends an external hyperlink to the paragraph.
*
* @param url The URL to the external target
* @param text The linked text
* @param paragraph the paragraph the link will be appended to.
*/
public static void appendExternalHyperlink(String url, String text, XWPFParagraph paragraph){
//Add the link as External relationship
String id=paragraph.getDocument().getPackagePart().addExternalRelationship(url, XWPFRelation.HYPERLINK.getRelation()).getId();
//Append the link and bind it to the relationship
CTHyperlink cLink=paragraph.getCTP().addNewHyperlink();
cLink.setId(id);
//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});
}
答案 1 :(得分:4)
目前,XWPF支持阅读和操作超链接,有关详细信息,请参阅XWPFHyperLinkRun和XWPFHyperlink。
目前没有任何用户面向代码来处理在XWPF中创建超链接,但是所有组件都在那里(处理低级超链接对象,能够在关系中添加超链接等)。将所有这些联系在一起以提供缺失功能的补丁将非常受到所有人的欢迎!
答案 2 :(得分:4)
所有
以上示例显示了如何创建外部超链接。对于需要创建内部超链接的用户,请参阅以下代码:
XWPFParagraph hyperPara = document.createParagraph();
hyperPara.setAlignment(ParagraphAlignment.CENTER);
addHyperlink(hyperPara, "Hyperlink Text", "Heading Text");
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});
//Create the formatting
CTFonts fonts = CTFonts.Factory.newInstance();
fonts.setAscii("Calibri Light" );
CTRPr rpr = ctr.addNewRPr();
CTColor colour = CTColor.Factory.newInstance();
colour.setVal("0000FF");
rpr.setColor(colour);
CTRPr rpr1 = ctr.addNewRPr();
rpr1.addNewU().setVal(STUnderline.SINGLE);
//Insert the linked text into the link
cLink.setRArray(new CTR[]{ctr});
}
答案 3 :(得分:2)
我担心Apache POI在处理Word文件方面并不比处理Excel文档时差。如果您处于开发的早期阶段,也许可以考虑转移到Docx4j。
干杯, 维姆