首页 > 解决方案 > 无法将字符串导出为 .xlsx 文件中的超链接 - Java 8 和 POI 3.17

问题描述

我尝试构建一个 Excel 文件,其中第一个单元格每次都是超链接。我在 Spring Boot API 中使用 Java 8 和 POI 3.17。excel 导出工作正常,但问题是,第一个单元格现在完全为空。我没有收到任何警告或错误或其他任何东西。有问题的代码:

  final XSSFWorkbook wb = exportHelperService.loadWorkbookTemplate(path);
  XSSFHyperlink url_link = wb.getCreationHelper().createHyperlink(HyperlinkType.URL) // definition for Hyperlink


  fillWorkbook(....) {  // here i gonna fill my workbook - everything works fine

    url_link.setAddress("http://www.google.de/");  // definition of url address - checked that its not empty

    exportHelperService.insertHyperlinkValue(url_link, "Cell_1", row);  // calls function that writes into the cell 1 - for all other cells there is NO problem

    // ... code that works fine ...

  }


  public void insertHyperlinkValue(XSSFHyperlink value, String columName, Row row) {
    if (value != null) {
        Cell cell = row.getCell(columnIndexMap.get(columName), CREATE_NULL_AS_BLANK);
        cell.setHyperlink(value); // <--- HERE IS THE PROBLEM
    }
}

我测试了 insertHyperlinkValue() 函数只打印一个字符串,它工作正常,但对于超链接它不想工作......我的假在哪里?非常感谢您的每一个回答!!!

标签: javaexcelspring-bootapache-poi

解决方案


单元格已经包含链接,它只是没有文本/样式。

XSSFWorkbook wb = new XSSFWorkbook();
XSSFHyperlink link = wb.getCreationHelper().createHyperlink(HyperlinkType.URL);
XSSFCellStyle hlinkstyle = wb.createCellStyle();
XSSFFont hlinkfont = wb.createFont();
hlinkfont.setUnderline(XSSFFont.U_SINGLE);
hlinkfont.setColor(IndexedColors.BLUE.index);
hlinkstyle.setFont(hlinkfont);
link.setAddress("http://www.google.de/");
Sheet s = wb.createSheet();
Row r = s.createRow(0);
Cell c = r.createCell(0);
c.setHyperlink(link);
c.setCellStyle(hlinkstyle);  //<-- make it look like link
c.setCellValue(link.getAddress());  // <-- important
wb.write(new FileOutputStream(new File("D:\\Test\\hyperlink.xlsx")));
wb.close();

您只需要设置单元格文本和样式就可以了。


推荐阅读