jeecg根据模板导出(java.io.FileNotFoundException: file:xx/templates/gp_export_template.xlsx(没有那个文件或目录))

使用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

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值