POI操作Excel---給單元格新增超連結(HSSF & XSSF & SXSSF)
阿新 • • 發佈:2018-11-07
1、xls格式---(HSSF)
HSSFWorkbook workbook = new HSSFWorkbook(); HSSFSheet sheet = workbook.createSheet("新增超連結"); HSSFRow row = sheet.createRow(0); HSSFCell cell = row.createCell(0); HSSFHyperlink link = new HSSFHyperlink(HSSFHyperlink.LINK_URL); link.setAddress("https://github.com/550690513"); cell.setHyperlink(link);// 設定超連結 cell.setCellValue("Fork me on Github");
2、xlsx格式---(XSSF & SXSSF)
2.1:錯誤寫法:XSSFWorkbook workbook = new XSSFWorkbook(); XSSFSheet sheet = workbook.createSheet(); XSSFRow row = sheet.createRow(0); XSSFCell cell = row.createCell(0); // 此處報'XSSFHyperlink(int)' has protected access in 'org.apache.poi.xssf.usermodel.XSSFHyperlink XSSFHyperlink link = new XSSFHyperlink(XSSFHyperlink.LINK_URL);// 無法例項化XSSFHyperlink物件 link.setAddress("https://github.com/550690513"); cell.setHyperlink(link); cell.setCellValue("Fork me on Github");
2.2:正確寫法:
XSSFWorkbook workbook = new XSSFWorkbook(); XSSFSheet sheet = workbook.createSheet(); XSSFRow row = sheet.createRow(0); XSSFCell cell = row.createCell(0); // 使用creationHelpper來建立XSSFHyperlink物件 CreationHelper createHelper = workbook.getCreationHelper(); XSSFHyperlink link = (XSSFHyperlink) createHelper.createHyperlink(Hyperlink.LINK_URL); link.setAddress("https://github.com/550690513"); cell.setHyperlink(link); cell.setCellValue("Fork me on Github");