- Apache POI Tutorial
- Apache POI - Home
- Apache POI - Overview
- Apache POI - Java Excel APIs
- Apache POI - Environment
- Apache POI - Core Classes
- Apache POI - Workbooks
- Apache POI - Spreadsheets
- Apache POI - Cells
- Apache POI - Fonts
- Apache POI - Formula
- Apache POI - Hyperlink
- Apache POI - Print Area
- Apache POI - Database
- Apache POI Resources
- Apache POI - Questions & Answers
- Apache POI - Quick Guide
- Apache POI - Useful Resources
- Apache POI - Discussion
Apache POI - 超链接
本章介绍如何向单元格中的内容添加超链接。通常,超链接用于访问任何 Web URL、电子邮件或外部文件。
以下代码显示如何在单元格上创建超链接。
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.ss.usermodel.IndexedColors; 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(IndexedColors.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.tutorialspoint.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.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(HyperlinkType.EMAIL); link.setAddress("mailto:contact@tutorialspoint.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文件如下所示 -