您的位置:首页 > 运维架构 > Linux

springBoot 使用easypoi,在linux服务器上无法 导出excel问题

2018-02-28 16:04 691 查看
使用的框架

excel工具 文档 http://www.afterturn.cn/doc/easypoi.html
根据文档,在windows上实现了excel下载功能,也是正常的。

但放在linux服务器上时,无法加载到excel模版

报错信息

2018-02-28 11:32:04,295 [http-nio-8000-exec-3] ERROR [cn.afterturn.easypoi.cache.ExcelCache] - java.lang.NullPointerException
com.google.common.util.concurrent.UncheckedExecutionException: java.lang.NullPointerException
at com.google.common.cache.LocalCache$Segment.get(LocalCache.java:2203)

excel模版路径
src--

------main

------resources(模版放在这个路径下)

easypoi的加载excel模版文件的源代码

package cn.afterturn.easypoi.cache.manager;

FileLoaderImpl

try {
//先用绝对路径查询,再查询相对路径
try {
fileis = new FileInputStream(url);
} catch (FileNotFoundException e) {
//获取项目文件
fileis = ClassLoader.getSystemResourceAsStream(url);
if (fileis == null) {
//最后再拿想对文件路径
String path = PoiPublicUtil.getWebRootPath(url);
fileis = new FileInputStream(path);
}
}
后面了解到springBoot的文件资源加载方式会有一些不同

参考如下的文章

Spring-boot 微服务jar包方式启动,获取jar内资源文件到本地磁盘
http://blog.csdn.net/zhangjian15/article/details/73277796
就改变了实现方案

写了一个方法:首先把找到的模版写到磁盘,再把路径传给easypoi的工具类

修改前的调用方式

TemplateExportParams params = new TemplateExportParams("excelTemplate/myRepay.xls");

修改后
TemplateExportParams params = new TemplateExportParams(convertTemplatePath("excelTemplate/myRepay.xls"));

工具类

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();
}

由于是赶项目,没有仔细研究了
有写的不对的地方,还请大家多多指正
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐