记录一次EasyPoi导出excel上线报空指针

问题源头:springBoot项目打jar包后文件资源加载方式不同,打包后Spring试图访问文件系统路径,但无法访问jar中的路径。

解决方案:可以使用 resource.getInputStream() 获取模板的文档流,重写到tomcat容器中并生成新的模板路径,按新的路径,导出excel即可。

public void exportExcel(List<Integer> ids, HttpServletResponse response) {
        //取到要导出的模板
        TemplateExportParams params = new TemplateExportParams(convertTemplatePath("\\static\\template\\溯源报表.xls"));
        System.out.println();
        //遍历信息使用工具类导出到
        if (null != params){
            //根据ids查询出对应的信息
            List<QrCodeBind> list = qrCodeBindMapper.selectByIds(ids);

            Map<String, Object> map = new HashMap<>();
            List<Map<String, Object>> listMap = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                Map<String, Object> lm = new HashMap<>();
                //put的键要跟excel模板中的名称一致
                String qrCodeNum = list.get(i).getQrCode();
                byte[] bytes = createQrCode(baseUrl+qrCodeNum, 256, 256);
                ImageEntity imageEntity = new ImageEntity(bytes, 256, 256);
                Date createTime = list.get(i).getCreateTime();
                lm.put("qrCodeNum", qrCodeNum);
                lm.put("batchNumberName", list.get(i).getBatchNumberName());
                lm.put("createTime",StringUtils.fromDate(createTime));
                lm.put("url",baseUrl+qrCodeNum);
                lm.put("qrCodeImg",imageEntity);
                listMap.add(lm);
            }
            map.put("maplist", listMap);
            Workbook workbook =  ExcelExportUtil.exportExcel(params, map);
            ServletOutputStream out = null;
            try {

                response.setContentType("application/vnd.ms-excel;charset=UTF-8");
                //设置导出Excel的名称
                response.setHeader("Content-disposition", "attachment;filename="+URLEncoder.encode("溯源报表.xls","UTF-8"));

                out=response.getOutputStream();
                workbook.write(out);
            }catch (IOException e){
                e.printStackTrace();
            }finally {
                if (null!=out){
                    try {
                        out.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    /**
     * 生成二维码
     * @param content
     * @param width
     * @param height
     * @return
     */
    private byte[] createQrCode(String content, int width, int height){
        QrConfig config = new QrConfig(width, height);

        // 设置边距,既二维码和背景之间的边距
        config.setMargin(3);
        // 高纠错级别
        config.setErrorCorrection(ErrorCorrectionLevel.H);
        // 设置前景色,既二维码颜色(青色)
        config.setForeColor(new Color(0,0,0).getRGB());
        // 设置背景色(灰色)
        config.setBackColor(new Color(242,242,242).getRGB());

        return QrCodeUtil.generatePng(content, config);
    }

    /*
        Resource读取文件存到Tomcat获取新的地址
    */
    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);
        // 文件存在时不再写入
        if (tempFile.exists()) {
            return tempFile.getPath();
        }
        File parentFile = tempFile.getParentFile();
        // 判断父文件夹是否存在
        if (!parentFile.exists()) {
            parentFile.mkdirs();
        }
        try {
            BufferedInputStream inputStream = new BufferedInputStream(resource.getInputStream());
            fileOutputStream = new FileOutputStream(tempFile);
            byte[] buffer = new byte[10240];
            int len = 0;
            while ((len = inputStream.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();
    }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值