我一直使用Java在excel中设置超链接列文件名包含文件夹名称中的空格(例如:Employee Details
)它将返回以下错误。我怀疑如何添加带空格名的超链接setAddress文件夹中。
File file=new File("/home/suser/Desktop/pathfile/Employee Details /1.pdf")
Hyperlink fileLink = createHelper.createHyperlink(Hyperlink.LINK_FILE);
fileLink.setAddress(file.getAbsolutePath());
错误:
Exception in thread "main" java.lang.IllegalArgumentException: Address of hyperlink must be a valid URI
at org.apache.poi.xssf.usermodel.XSSFHyperlink.validate(XSSFHyperlink.java:212)
at org.apache.poi.xssf.usermodel.XSSFHyperlink.setAddress(XSSFHyperlink.java:194)
at com.example.excelapp.ExcelApp.main(ExcelApp.java:83)
Caused by: java.net.URISyntaxException: Illegal character in path at index 27: /home/user/Desktop/class Name/ExcelApp/
'/home/user/Desktop/pathfile/Employee Details /1.pdf'
at java.net.URI$Parser.fail(URI.java:2810)
at java.net.URI$Parser.checkChars(URI.java:2983)
at java.net.URI$Parser.parseHierarchical(URI.java:3067)
at java.net.URI$Parser.parse(URI.java:3025)
at java.net.URI.<init>(URI.java:577)
at org.apache.poi.xssf.usermodel.XSSFHyperlink.validate(XSSFHyperlink.java:210)
答案 0 :(得分:1)
即使指向文件的链接,超链接也始终链接到URI。 URI必须是URI编码的。因此,空格将被编码为%20
。
知道这一点,如果涉及到超链接,我会使用URI。
工作示例:
import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import java.io.*;
import java.io.IOException;
class ExcelCellHyperlink {
public static void main(String[] args) {
try {
Workbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet();
File filePDF = new File("/home/axel/Dokumente/JAVA/poi/poi-3.14/Employee Details /1.pdf");
System.out.println(filePDF.toURI().toString());
//create a cell with a link to absolute file URI
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
Hyperlink fileLink = wb.getCreationHelper().createHyperlink(Hyperlink.LINK_FILE);
fileLink.setAddress(filePDF.toURI().toString());
cell.setCellValue("link to absolute file URI");
cell.setHyperlink(fileLink);
//create a file with the file path for this Excel file
File thisExcelFilePath = new File("/home/axel/Dokumente/JAVA/poi/poi-3.14/");
System.out.println(thisExcelFilePath.toURI().toString());
//create a URI to the PDF file relative to the path of this Excel file
String relativeURI = thisExcelFilePath.toURI().relativize(filePDF.toURI()).toString();
System.out.println(relativeURI);
//create a cell with a link to relative file URI
row = sheet.createRow(2);
cell = row.createCell(0);
fileLink = wb.getCreationHelper().createHyperlink(Hyperlink.LINK_FILE);
fileLink.setAddress(relativeURI);
cell.setCellValue("link to relative file URI");
cell.setHyperlink(fileLink);
FileOutputStream fileOut = new FileOutputStream(thisExcelFilePath.getPath() + "/ExcelCellHyperlink.xlsx");
wb.write(fileOut);
fileOut.close();
} catch (IOException ioex) {
ioex.printStackTrace();
}
}
}
此示例还说明了如何创建相对于此Excel文件路径的超链接URI。这更实际,因为绝对路径将高度依赖于它们是否可以从Excel应用程序访问。