栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

AutoPoi Linux上TemplateExportParams报空指针异常

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

AutoPoi Linux上TemplateExportParams报空指针异常

项目场景

        Springboot使用AutoPoi模版注解方式导出数据


问题描述

        Springboot使用AutoPoi部署在Linux上TemplateExportParams类获取模版路径报空指针异常:

String path = "static/exportTemplate/xxxx.xlsx";
TemplateExportParams templateExportParams = new TemplateExportParams(path);

解决方案
1、新建工具类,将模版写到临时目录下,再读取临时目录下的模板即可
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;


@Slf4j
public class TemplatePathUtils {

    private TemplatePathUtils() {
    }

    private static final String OS_NAME = "os.name";

    private static final String OS_VERSION = "Windows";

    public static final String CATALINA_HOME = "catalina.home";

    public static String getTemplatePath(String path) {
        if (System.getProperties().getProperty(OS_NAME).contains(OS_VERSION)) {
            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);
        // 文件存在时 不再写入
        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) {
            log.error("获取文件路径异常,异常原因{}", e, e.getMessage());
        } finally {
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    log.error("获取文件路径关闭文件流异常,异常原因{}", e, e.getMessage());
                }
            }
        }
        return tempFile.getPath();
    }
}

2、调用工具类获取模版路径

String path = TemplatePathUtils.getTemplatePath("static/exportTemplate/XXXX.xlsx");
TemplateExportParams templateExportParams = new TemplateExportParams(path);

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1027229.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号