2015-12-21 154 views
0

我的超鏈接文件駐留在Whois目錄中,並且dir和Excel文件都位於同一父目錄中。由於相對路徑,我無法通過超鏈接訪問我的文件。我需要將這個Excel文件發送給幾個收件人,而無需更改其選項。我試過getPath(),getCanonicalPath()和getAbsolutePath()無濟於事。這裏是我的代碼:無法打開超鏈接文件Apache POI

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

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

+0

在我的情況下,案件和java文件都在同一個文件夾中.... Whois目錄和XLSX文件都在同一個目錄中..我如何指定相對路徑。 –

+0

@MallikKumar我已經改變了答案,請看看 – dlopatin

+0

可以說我有一個名爲parent的文件夾... parent包含Whois和Excel文件。 Excel文件鏈接到fileToLink.txt的Whois文件夾中。相對地址是什麼? –