使用jeecg-boot开发,在resources目录中添加了一个模板文件,在windows中,通过以下方式设置excel导出配置params,
Resource resource = new ClassPathResource("templates/xx.xlsx");
TemplateExportParams params = new TemplateExportParams(resource.getPath());
没有任何的问题。
但是在打成jar后运行,结果无法读取到文件。在jar里面对应的class路径下可以看到该文件,确定是有打包进去的。
在windows ide调试时文件是真实存在于磁盘的某个目录。此时通过获取文件路径,是可以正常读取。但是打包成jar以后,实际上文件是存在于jar这个文件里面的资源文件。在磁盘是没有真实路径的。所以通过绝对地址无法正确获取文件。
解决方案:将模板文件拷贝一份写入硬盘,返回绝对地址:
public static String convertTemplatePath(String path) {
// 如果是windows 则直接返回
// if (System.getProperties().getProperty("os.name").contains("Windows")) {
// return path;
// }
Resource resource = new ClassPathResource(path);
FileOutputStream fileOutputStream = null;
// 将模版文件写入到 tomcat临时目录
String folder = System.getProperty("catalina.home");
File tempFile = new File(folder + File.separator + path);
// System.out.println("文件路径:" + tempFile.getPath());
// 文件存在时 不再写入
if (tempFile.exists()) {
return tempFile.getPath();
}
File parentFile = tempFile.getParentFile();
// 判断父文件夹是否存在
if (!parentFile.exists()) {
parentFile.mkdirs();
}
try {
BufferedInputStream bufferedInputStream = new BufferedInputStream(resource.getInputStream());
fileOutputStream = new FileOutputStream(tempFile);
byte[] buffer = new byte[10240];
int len = 0;
while ((len = bufferedInputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return tempFile.getPath();
}
并将excel导出参数设为以下:
TemplateExportParams params = new TemplateExportParams(convertTemplatePath("templates/xx.xlsx"));
代码原文链接:https://blog.csdn.net/KokJuis/article/details/80059184