本文将介绍使用spire.xls for java给excel文档添加超链接的方法,这里支持添加多种不同类型的链接,如url网页链接、workbook工作簿链接、file文档链接、unc网络路径链接等。
import com.spire.xls.*;
public class addhyperlink {
public static void main(string[] args) {
//创建workbook实例
workbook wb = new workbook();
//加载excel文档
wb.loadfromfile("test.xlsx");
//获取工作表
worksheet sheet = wb.getworksheets().get(0);
//添加url链接,链接到网页地址
hyperlink urllink = sheet.gethyperlinks().add(sheet.getcellrange("b3"));
urllink.settexttodisplay(sheet.getcellrange("b3").gettext());
urllink.gettype().compareto(hyperlinktype.url);
urllink.setaddress("https://www.baidu.com/");
//添加url链接,链接到邮件地址
hyperlink maillink = sheet.gethyperlinks().add(sheet.getcellrange("d3"));
maillink.settexttodisplay(sheet.getcellrange("d3").gettext());
maillink.gettype().compareto(hyperlinktype.url);
maillink.setaddress("mailto: support @ e-iceblue.com");
//添加file文档链接,链接到指定文档
hyperlink filelink = sheet.gethyperlinks().add(sheet.getcellrange("b7"));
filelink.settexttodisplay(sheet.getcellrange("b7").gettext());
filelink.gettype().compareto(hyperlinktype.file);
filelink.setaddress("e:\\idea\\sample.docx");
// 添加workbook文档链接,链接到工作簿文档(这里链接到测试文档中的指定sheet中的指定单元格)
hyperlink wblink = sheet.gethyperlinks().add(sheet.getcellrange("d7"));
wblink.gettype().compareto(hyperlinktype.workbook);
wblink.settexttodisplay(sheet.getcellrange("d7").gettext());
wblink.setaddress("sheet2!b5");
//添加unc链接,链接到网络路径
hyperlink unclink = sheet.gethyperlinks().add(sheet.getcellrange("b11"));
unclink.gettype().compareto(hyperlinktype.unc);
unclink.settexttodisplay(sheet.getcellrange("b11").gettext());
unclink.setaddress("\\192.168.1.108");
//保存文档
wb.savetofile("addhyperlink.xlsx",excelversion.version2010);
wb.dispose();
}
}
超链接添加效果: