java - 无法将字符串导出为 .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() 函数只打印一个字符串,它工作正常,但对于超链接它不想工作......我的假在哪里?非常感谢您的每一个回答!!!
解决方案
单元格已经包含链接,它只是没有文本/样式。
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();
您只需要设置单元格文本和样式就可以了。
推荐阅读
- python - 读取 CSV 后具有奇怪值的 Spark 数据帧
- php - 在 Wordpress 中仅显示一篇最新文章
- mongodb - mongodb聚合函数并根据条件返回结果
- oracle - Oracle dbms_aq.dequeue
- python - 我无法在 pip install 上安装模块,它给出红色文本错误
- flutter - parse_server_sdk 和 parse_server 有什么区别?
- html - CSS - 如何在表单输入中每 3 个字符放置一个空格?
- c# - 不存在 LayerHost 的 Blazor Fluent UI 下拉问题
- javascript - 转到给定的 URL(如果我们不在那里),显示表单并滚动到它
- javascript - 重构验证处理和消息传递