Apache POI超鏈接

本章介紹瞭如何爲超鏈接添加到內容的單元格。超鏈接通常被用來訪問任何網站的網址,電子郵件或外部文件。

下面的代碼演示如何創建單元格的超鏈接。

import java.io.File;
import java.io.FileOutputStream;
import org.apache.poi.common.usermodel.Hyperlink;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFHyperlink;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class HyperlinkEX
{
public static void main(String[] args) throws Exception
{
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet spreadsheet = workbook
.createSheet("Hyperlinks");
XSSFCell cell;
CreationHelper createHelper = workbook
.getCreationHelper();
XSSFCellStyle hlinkstyle = workbook.createCellStyle();
XSSFFont hlinkfont = workbook.createFont();
hlinkfont.setUnderline(XSSFFont.U_SINGLE);
hlinkfont.setColor(HSSFColor.BLUE.index);
hlinkstyle.setFont(hlinkfont);
//URL Link
cell = spreadsheet.createRow(1)
.createCell((short) 1);
cell.setCellValue("URL Link");
XSSFHyperlink link = (XSSFHyperlink)createHelper
.createHyperlink(Hyperlink.LINK_URL);
link.setAddress("http://www.yiibai.com/" );
cell.setHyperlink((XSSFHyperlink) link);
cell.setCellStyle(hlinkstyle);
//Hyperlink to a file in the current directory
cell = spreadsheet.createRow(2)
.createCell((short) 1);
cell.setCellValue("File Link");
link = (XSSFHyperlink)createHelper
.createHyperlink(Hyperlink.LINK_FILE);
link.setAddress("cellstyle.xlsx");
cell.setHyperlink(link);
cell.setCellStyle(hlinkstyle);
//e-mail link
cell = spreadsheet.createRow(3)
.createCell((short) 1);
cell.setCellValue("Email Link");
link = (XSSFHyperlink)createHelper
.createHyperlink(Hyperlink.LINK_EMAIL);
link.setAddress(
"mailto:contact@yiibai.com?"
+"subject=Hyperlink");
cell.setHyperlink(link);
cell.setCellStyle(hlinkstyle);
FileOutputStream out = new FileOutputStream(
new File("hyperlink.xlsx"));
workbook.write(out);
out.close();
System.out.println("hyperlink.xlsx written successfully");
}
}

保存上面的代碼到文件HyperlinkEX.java。並從命令提示符編譯執行它如下。

$javac HyperlinkEX.java
$java HyperlinkEX

它會生成一個名爲hyperlink.xlsx在當前目錄中的Excel文件並顯示在命令提示符處輸出:

hyperlink.xlsx written successfully

hyperlink.xlsx文件如下所示。

Hyperlink