首页 > 解决方案 > POI - get.hyperlink() 未检索单元格的最新超链接

问题描述

在这里,我在同一个单元格中用第二个超链接覆盖了第一个超链接,并且get.hyperlink()方法总是拉取第一次写入单元格中的超链接。

任何关于这方面的帮助都会很棒!!提前致谢

下面是我的代码和输出:

public static void main(String[] args) {
    ExcelUtils2.writeHyperLink("DashboardCopy", 1, 1, "test1", "https://google.com");
    ExcelUtils2.writeHyperLink("DashboardCopy", 1, 1, "test2", "https://facebook.com");
    String dtr = ExcelUtils2.getCellHyperlink(1, 1);
    System.out.println("Hyperlink of the cell is >> " + dtr);
}


public static synchronized void writeHyperLink(String workBookName, int irow, int icol, String ivalue, String iUrl)
        throws InvalidFormatException, IOException {
    FileInputStream excelFile = new FileInputStream(excelSource);
    excelWBook = new XSSFWorkbook(excelFile);
    excelWSheet = excelWBook.getSheet(workBookName);
    createHelper = excelWBook.getCreationHelper();
    XSSFRow row = excelWSheet.getRow(irow);
    XSSFCell cell = row.createCell(icol);
    cell.setCellValue(ivalue);
    XSSFHyperlink link = (XSSFHyperlink) createHelper.createHyperlink(HyperlinkType.URL);
    link.setAddress(iUrl);
    cell.setHyperlink(link);
    FileOutputStream fos = new FileOutputStream(excelSource);
    excelWBook.write(fos);
    fos.close();

}

public static String getCellHyperlink(int rowNum, int colNum) throws Exception {
    FileInputStream excelFile = new FileInputStream(excelSource);
    excelWBook = new XSSFWorkbook(excelFile);
    excelWSheet = excelWBook.getSheet("DashboardCopy");
    XSSFRow row = excelWSheet.getRow(rowNum);
    XSSFCell cell = row.getCell(colNum);
    XSSFHyperlink link = cell.getHyperlink();
    String cellData = link.getAddress();
    // System.out.println(link.getAddress());
    return cellData;
}

输出:单元格的超链接是>> https://google.com

预期输出:它应该打印https://facebook.com

标签: javaexcelapache-poi

解决方案


我会在设置之前尝试删除超链接

 cell.removeHyperlink();
 cell.setHyperlink(link);

推荐阅读