在Java程式設計中,如何向單元格的內容新增超連結?
注意:需要存取網址:http://poi.apache.org/download.html , 下載一個Apache POI軟體包。這裡下載最新版本:poi-bin-3.17-20170915.tar.gz解壓並將全部
.jar
檔案匯入 。
需要匯入全部包,如下圖所示 -
參考範例:
http://poi.apache.org/spreadsheet/quick-guide.html
以下是使用Java向單元格的內容新增超連結的程式。
package com.yiibai;
import java.io.File;
import java.io.FileOutputStream;
import org.apache.poi.common.usermodel.Hyperlink;
import org.apache.poi.common.usermodel.HyperlinkType;
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 AddHyperlinkToCell {
public static void main(String[] args) throws Exception {
// Create a Workbook
XSSFWorkbook workbook = new XSSFWorkbook();
// Create a Spread Sheet
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(HyperlinkType.URL);
link.setAddress("https://www.tw511.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(HyperlinkType.URL);
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(HyperlinkType.EMAIL);
link.setAddress("mailto:[email protected]?subject=Hyperlink");
cell.setHyperlink(link);
cell.setCellStyle(hlinkstyle);
FileOutputStream out = new FileOutputStream(new File("addHyperlink.xlsx"));
// Writing the content
workbook.write(out);
out.close();
System.out.println("hyperlink.xlsx written successfully");
}
}
執行上面範例程式碼,得到以下結果 -
hyperlink.xlsx written successfully
建立的Excel檔案內容,如下所示 -