Home » excel » java – Multiple Hyperlinks in Apache POI

java – Multiple Hyperlinks in Apache POI

Posted by: admin May 14, 2020 Leave a comment

Questions:

Is it possible to have same hyperlink multiple times in a single excel sheet?

Hyperlink link = createHelper.createHyperlink(Hyperlink.LINK_URL);
link.setAddress("http://poi.apache.org/");

I have used the above code for creating the hyperlink and the following code to generate the rows and columns for the excel sheet.

 Row title = null;
 Cell reportNames = null;

   /*
       I am processing some queries here
   */


      while(rs.next()){
            title = sheet.createRow(idx); 
            reportNames = title.createCell(0);
            reportNames.setCellValue(rs.getString(1));
            reportNames.setHyperlink(link); 
            idx++;
            sheet.autoSizeColumn(0);

          }
        }

My problem is the hyperlink is displayed/works only for the content of last row. I mean, only the last row is clickable and it redirects me properly where as the others are not set as hyperlinks?
Is there any restriction such that there can be only one hyperlink pointing to the same web address? Or am I doing anything wrong?

How to&Answers:

You must create a new Hyperlink object every time you want to create a hyperlinked cell. When you call setHyperlink on the Cell object, it sets a reference to itself for a hyperlink. Here’s an extract from the org.apache.poi.xssf.usermodel.XSSFCell class (lines 913 – 921 in version 3.9):

public void setHyperlink(Hyperlink hyperlink) {
    XSSFHyperlink link = (XSSFHyperlink)hyperlink;

    // Assign to us
    link.setCellReference( new CellReference(_row.getRowNum(), _cellNum).formatAsString() );

    // Add to the lists
    getSheet().addHyperlink(link);
}

It becomes evident by looking at link.setCellReference(... method call.