0

我正在尝试使用 APACHE POI XSSF 使用相对路径创建指向文件的超链接。打开使用 Microsft Excel 创建的 .xlsx 文件时,相对路径已被修改,并且链接不正确。Microsoft Excel 在路径前添加了一些“../../”。我尝试用 OpenOffice 打开它,它工作正常。我也尝试过使用 HSSF,它在 Microsoft Excel 和 OpenOffice 中都可以使用。知道为什么会这样吗?这是一个示例代码:

import java.io.File;
import java.io.FileOutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import org.apache.poi.hssf.usermodel.HSSFHyperlink;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.Hyperlink;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelHyperlinks {
 public static void main(String[] args) throws Exception{
     /* Create Workbook and Worksheet */
     XSSFWorkbook my_workbook = new XSSFWorkbook();
     XSSFSheet my_sheet = my_workbook.createSheet("Cell Hyperlink");
     CreationHelper createHelper = my_workbook.getCreationHelper();
     Hyperlink  url_link=createHelper.createHyperlink(HSSFHyperlink.LINK_URL);
     Hyperlink  file_link=createHelper.createHyperlink(HSSFHyperlink.LINK_FILE);
     Hyperlink  email_link=createHelper.createHyperlink(HSSFHyperlink.LINK_EMAIL);

     /* Define the data for these hyperlinks */
     url_link.setAddress("http://www.google.com");
     try {
         file_link.setAddress((URLEncoder.encode("Encuesta de bienvenida","UTF-8")+"/"+"E18").replace("\\", "/").replace("+","%20"));
     } catch (UnsupportedEncodingException e) {
         e.printStackTrace();
     }
     System.out.println("addres--> " + file_link.getAddress());
     email_link.setAddress("mailto:test@gmail.com");

     /* Attach these links to cells */
     Row row = my_sheet.createRow(0);                
     Cell cell = row.createCell(0);
     cell.setCellValue("Take me to Google");         
     cell.setHyperlink(url_link);

     row = my_sheet.createRow(1);            
     cell = row.createCell(1);
     cell.setCellValue("Click to Open the file");            
     cell.setHyperlink(file_link);

     row = my_sheet.createRow(2);            
     cell = row.createCell(2);
     cell.setCellValue("Send an Email");             
     cell.setHyperlink(email_link);

     /* Write changes to the workbook */
     FileOutputStream out = new FileOutputStream(new File("C:/cell_hyperlink_example.xlsx"));
     my_workbook.write(out);
     out.close();
 }

}

4

1 回答 1

1

这似乎不是问题。它是 excel 功能,无论您提供什么路径,它都会创建从 excel 位置到超链接文件位置的相对路径。

每个“../”代表一个目录。如果您从当前的 Excel 工作表位置通过这种方式移动,您将到达超链接文件目录。

例如,如果您的 excel 工作表在 sayc:\folder1\folder2\excelDir\test.xls并且超链接文件的目录是 sayc:\folder1\folder3\imageDir\test.jpg

在excel中标记的相对路径就像

../../folder3/imageDir/test.jpg

首先../,我们将从 移动test.xlsexcelDir,其次,../我们将从现在移动excelDirfolder2 相同的目录包含folder3,因此它将从这里继续到test.jpg

于 2013-09-03T11:49:12.667 回答