无法打开超链接的文件Apache POI

我的超链接文件驻留在Whois目录中,并且dir和Excel文件都位于同一个父目录中。 由于相对path,我无法通过超链接访问我的文件。 我需要将这个Excel文件发送给几个收件人,而不会改变他们的选项。 我已经尝试getPath(),getCanonicalPath()和getAbsolutePath()无济于事。 这是我的代码:

public void writeTheFile() throws Exception { int rowNum=-1; String line = ""; XSSFWorkbook workBook = new XSSFWorkbook(); XSSFSheet sheet = workBook.createSheet("Contact & Whois"); XSSFCreationHelper helper = workBook.getCreationHelper(); BufferedReader br = new BufferedReader(new FileReader(INPUT_FILE)); while((line = br.readLine()) != null) { rowNum++; XSSFRow currentRow=sheet.createRow(rowNum); currentRow.createCell(0).setCellValue(line.trim()); currentRow.createCell(1); XSSFHyperlink file_link_downloads = helper.createHyperlink(Hyperlink.LINK_FILE); Cell cell = sheet.getRow(rowNum).getCell(1); try { File f = new File("Whois/" + line + ".whois.txt"); if(f.exists()) { cell.setCellValue("[Whois]"); String path = f.getPath(); file_link_downloads.setAddress(path); cell.setHyperlink((org.apache.poi.ss.usermodel.Hyperlink) file_link_downloads); } else { cell.setCellValue("-NA-"); } } catch (Exception e) { System.out.println("Error in setting up download link"); e.printStackTrace(); } } 

在Windowspath正在逐字地坚持在另一台计算机上。

Excel从当前文件位置设置相对链接。 所以,你必须检查文件的存在,然后设置相对path。

例:

 Hyperlink hyperlink = creationHelper.createHyperlink(Hyperlink.LINK_FILE); String relativePath = "../parentdir/fileToLink.txt"; hyperlink.setAddress(relativePath); hyperlink.setLabel("Link to file"); cell.setHyperlink(hyperlink); cell.setCellValue("Link to file"); cell.setCellType(Cell.CELL_TYPE_STRING); 

如果excel文件与链接文件在同一目录下,只需指定链接为hyperlink.setAddress("fileToLink.txt")