我用java的JacobExcelTool工具类调用本地excel的宏命令,idea测试没问题,用javafx打包成exe之后不能运行,应该是找不到这个文件,请问下怎么解决?
JacobExcelTool tool = new JacobExcelTool();
String path = getClass().getResource("").getPath().substring(1);
URL resource = getClass().getResource("/REFPROP.XLA");
File file1 = new File(resource.toURI());
File file = new File("REFPROP.XLA");
if(file1.exists()){
System.out.println("存在");
System.out.println(file.getPath());
}
//打开
tool.OpenExcel( file1.getAbsolutePath(), false, false);
// tool.OpenExcel("C:/Program Files (x86)/REFPROP/REFPROP.XLA", true, false);
Dispatch sheet = tool.getSheetByName("Sheet1");
用文件的绝对路径,不要用相对路径。或将文件放到项目根目录下,再使用相对路径
打包后可能是文件路径问题导致无法找到文件。建议把REFPROP.XLA文件打包到程序的根目录下,然后使用绝对路径来指向该文件,例如:
File file = new File("REFPROP.XLA");
tool.OpenExcel(file.getAbsolutePath(), false, false);
或者在程序启动时将该文件复制到临时目录,然后使用临时目录中的文件:
String tempFilePath = System.getProperty("java.io.tmpdir") + "/REFPROP.XLA";
File tempFile = new File(tempFilePath);
if (!tempFile.exists()) {
InputStream resourceStream = getClass().getResourceAsStream("/REFPROP.XLA");
OutputStream outputStream = new FileOutputStream(tempFile);
byte[] buffer = new byte[1024];
int length;
while ((length = resourceStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
outputStream.close();
resourceStream.close();
}
tool.OpenExcel(tempFile.getAbsolutePath(), false, false);
希望能够解决你的问题!