SpringBoot+Hutool 文件导出Excel

Hutool-poi是针对Apache POI的封装,因此需要用户自行引入POI库,Hutool默认不引入。到目前为止,Hutool-poi支持:

Excel文件(xls, xlsx)的读取(ExcelReader)
Excel文件(xls,xlsx)的写出(ExcelWriter)

使用

引入POI依赖

推荐引入poi-ooxml,这个包会自动关联引入poi包,且可以很好的支持Office2007+的文档格式

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>${poi.version}</version>
</dependency>

如果需要使用Sax方式读取Excel,需要引入以下依赖(POI-4.x以上这个非必须):

<dependency>
    <groupId>xerces</groupId>
    <artifactId>xercesImpl</artifactId>
    <version>${xerces.version}</version>
</dependency>

说明
hutool-4.x的poi-ooxml 版本需高于 3.17(别问我3.8版本为啥不行,因为3.17 > 3.8 )
hutool-5.x的poi-ooxml 版本需高于 4.1.2
hutool-5.6.x支持poi-ooxml 版本高于 5.0.0
xercesImpl版本高于2.12.0(非必须)

引入后即可使用Hutool的方法操作Office文件了,Hutool提供的类有:

ExcelUtil Excel工具类,读取的快捷方法都被封装于此
ExcelReader Excel读取器,Excel读取的封装,可以直接构造后使用。
ExcelWriter Excel生成并写出器,Excel写出的封装(写出到流或者文件),可以直接构造后使用。

常见问题

Maven依赖

<dependency>
                <groupId>cn.hutool</groupId>
                <artifactId>hutool-all</artifactId>
                <version>5.8.22</version>
            </dependency>
 <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>4.1.2</version>
        </dependency>

示例接口

/**
     * 导出对账单
     *
     * @param request  request
     * @param response response
     */
    @RequestMapping(value = "/exportPaymentInfo", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public void export(HttpServletRequest request, HttpServletResponse response) throws IOException {
        SessionUser sessionUser = super.getSessionUser();
        if (null == sessionUser) {
            throw new BusinessException("用户登录状态过期");
        }
        OutputStream outputStream = null;
        File file = null;
        Object paymentVIewVOStr = redisTemplate.opsForValue().get("paymentVIewVO");
        PaymentVIewVO paymentVIewVO;
        if (null != paymentVIewVOStr) {
            paymentVIewVO = JSON.parseObject(paymentVIewVOStr.toString(), PaymentVIewVO.class);
        } else {
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write("{\n" +
                    "  \"@type\": \"com.cztech.common.domain.model.Result\",\n" +
                    "  \"msg\": \"ErrorCode:500, 导出失败,请重新查询数据再尝试导出\",\n" +
                    "  \"success\": false\n" +
                    "}");
            return;
        }
        paymentVIewVO.setFlag(true);
        try {
            String os = System.getProperty("os.name");
            String filePath = "/tmp/tempPayment.xlsx";
            if (os.toLowerCase().startsWith("win")) {
                filePath = "d:/tmp/tempPayment.xlsx";
            }
            ExcelWriter writer = ExcelUtil.getWriter(filePath);
            //自定义标题别名
            writer.addHeaderAlias("successTime", "交易成功时间");
            writer.addHeaderAlias("createTime", "交易创建时间");
            writer.addHeaderAlias("orderNo", "业务订单号");
            writer.addHeaderAlias("channelReturnMessage", "原业务订单号");
            writer.addHeaderAlias("goodsName", "业务来源");
            writer.addHeaderAlias("transactionType", "交易类型");
            writer.addHeaderAlias("amount", "交易金额");
            writer.addHeaderAlias("goodsType", "分账方收款主体");
            writer.addHeaderAlias("price", "分账金额");
            writer.addHeaderAlias("paymentNo", "渠道的商户订单号");

            // 默认的,未添加alias的属性也会写出,如果想只写出加了别名的字段,可以调用此方法排除之
            writer.setOnlyAlias(true);
            Result<List> paymentVOList = paymentService.listReconciliationListALl(paymentVIewVO);
            if (!paymentVOList.isSuccess()) {
                response.setContentType("application/json;charset=utf-8");
                response.getWriter().write("{\n" +
                        "  \"@type\": \"com.cztech.common.domain.model.Result\",\n" +
                        "  \"msg\": "+paymentVOList.getMsg()+",\n" +
                        "  \"success\": false\n" +
                        "}");
                return;
            }
            writer.write(paymentVOList.getResponse(), true);
            writer.flush();
            String code = paymentVOList.getCode();
            if (StringUtils.isNotBlank(code)) {
                paymentVIewVO.setFlag(false);
                int currentNumber = Integer.parseInt(code);
                int index = currentNumber % 1000;
                for (int i = 0; i < index + 1; i++) {
                    paymentVIewVO.setCurrentPage(i + 2);
                    paymentVIewVO.setPageSize(currentNumber);
                    Result<List> paymentVOList2 = paymentService.listReconciliationListALl(paymentVIewVO);
                    if (paymentVOList2.isSuccess()) {
                        writer.write(paymentVOList2.getResponse(), true);
                        writer.flush();
                    }
                }
            }
            writer.close();
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            String yyyyMMdd = DateUtil.format(new Date(), "yyyyMMdd");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(yyyyMMdd + "对账明细数据.xlsx", "UTF-8"));
            outputStream = response.getOutputStream();
             file = new File(filePath);
            FileInputStream inputStream = new FileInputStream(file);
            IOUtils.copy(inputStream, outputStream);
        } catch (Exception e) {
            e.printStackTrace();

        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (file != null) {
                if (file.exists()) {
                    file.delete();
                }
            }
        }
    }

posted on 2024-10-14 11:00  白嫖老郭  阅读(201)  评论(0编辑  收藏  举报

导航