【问题标题】:Unable to open hyperlinked file Apache POI无法打开超链接文件 Apache POI
【发布时间】:2016-03-27 18:39:14
【问题描述】:

我的超链接文件位于 Whois 目录中,并且目录和 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 路径正在逐字保存在另一台计算机上。

【问题讨论】:

    标签: java excel hyperlink apache-poi


    【解决方案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")即可。

    【讨论】:

    • 在我的情况下,案例和 java 文件都在同一个文件夹中...... Whois 目录和 XLSX 文件都在同一个目录中......我如何指定相对路径。
    • @MallikKumar 我改了答案,请看一下
    • 假设我有一个名为 parent 的文件夹... parent 包含 Whois 和 Excel 文件。 Excel 文件链接到 FileToLink.txt 的 Whois 文件夹。相对地址是什么?
    • @MallikKumar 如果excel文件与Whois目录同级,则相对路径为Whois/fileToLink.txt
    • 这正是我在我的代码中尝试过的...... File f = new File("Whois/" + line + ".whois.txt");
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多