无法打开超链接文件Apache POI

时间:2015-12-21 16:11:03

标签: java excel hyperlink apache-poi

我的超链接文件位于Whois dir中,dir和Excel文件都位于同一个父目录中。由于相对路径,我无法通过超链接访问我的文件。我需要将此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();
        }
    }

在Windows路径上逐字地保留在另一台计算机上。

1 个答案:

答案 0 :(得分:1)

Excel设置当前文件位置的相对链接。因此,您必须检查文件是否存在,然后设置相对路径。

示例:

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")