EsayPoi模板导出在Linux上的导出问题(解)

博客指出Linux与Windows环境在路径解析模板时会出现问题,导致空指针异常。通过添加工具方法,将原代码中的路径使用转换方法处理,即TemplateExportParams params = new TemplateExportParams(convertTemplatePath(\excel/XXXXX.xlsx\)); 可解决Linux环境上的空指针异常问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

由于Linux与Windows环境上路径解析模板会有问题:会爆空指针异常

所以在TemplateExportParams params = new TemplateExportParams("excel/XXXXX.xlsx");

先添加一个工具方法:

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

最后原代码改成

TemplateExportParams params = new TemplateExportParams(convertTemplatePath("excel/XXXXX.xlsx"));

这样就会解决Linux环境上的空指针异常问题。

参考https://blog.youkuaiyun.com/zx1323/article/details/79401005

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值