easyexcel根据模板导出数据

1,709 阅读1分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

已经无法满足正常列表数据的导出,该死的甲方爸爸出了新的需求,根据一个模板进行导出所勾选的数据去导出

准备工作

引入jar包依赖,坐标如下

<dependency>
	<groupId>com.alibaba</groupId>
	<artifactId>easyexcel</artifactId>
	<version>2.2.6</version>
</dependency>

excel模板文件示例

在这里插入图片描述

excel模板文件改造

这里需要将要渲染的数据 设置变量 总金额变量设为{price} 总笔数变量设为{total} 四个列表数据分别是 {.account} {.order} {.name} {.remark}

ps:普通变量用花括号包裹即可,列表数据的变量记得加上. 而这些名字 是跟 后端处理的数据的key 要对应的上~~~

最终效果如下: 在这里插入图片描述

记得改完 放到路径下 /home (我是这样放的)

控制层代码

//接收参数
@RequestMapping(value = "/patchExport")
public void patchExport(String type, String idListStr,HttpServletResponse response) throws IOException {

        OrderUserDTO orderUserDTO = new OrderUserDTO();
        orderUserDTO.setType(type);
        //如果有选中复选框的话
        if (StringUtils.isNotNullAndBlank(idListStr)){
            //处理list
            List<String> idList = Arrays.asList(idListStr.split(","));
            orderUserDTO.setIdList(idList);
        }
        //这里进行查询
        List<OrderUserDTO> l = orderUserService.listBySearch(orderUserDTO);
        orderUserService.patchExport(list, response);
    }

业务层代码

    public void patchExport(List<OrderUserVO> list, HttpServletResponse response) throws IOException {
        OutputStream out = null;
        BufferedOutputStream bos = null;
        try {
        	//这个excel.path 是配置 上面模板的路径
            String templateFileName = MyConfiguration.create().getString("excel.path");
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            //导出的文件名
            String fileName = URLEncoder.encode("订单明细.xls", "utf-8");
            response.setHeader("Content-disposition", "attachment; filename=" + new String(fileName.getBytes("UTF-8"), "ISO-8859-1"));
            out = response.getOutputStream();
            bos = new BufferedOutputStream(out);
			
            BigDecimal totalPrice = BigDecimal.ZERO;//
            Integer totalCount = Constants.Ints.ZERO;
            //这个OrderUserCustomExcelDTO 的属性就是对应 上面excel的列表变量
            List<OrderUserCustomExcelDTO> voList = new ArrayList<>();
            if (!CollectionUtils.isEmpty(list)) {
                for (OrderUserVO dto : list) {
                    OrderUserCustomExcelDTO excelDTO = new OrderUserCustomExcelDTO();
                    //这里去set数据
                    totalPrice = totalPrice.add(dto.getOrderprice());
                    totalCount += 1;
                    voList.add(excelDTO);
                }
            }
            // 头的策略
            WriteCellStyle headWriteCellStyle = new WriteCellStyle();
            // 内容的策略
            WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
            //设置 自动换行
            contentWriteCellStyle.setWrapped(true);
            //设置 垂直居中
            contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
            //设置 水平居中
            contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);

            HorizontalCellStyleStrategy horizontalCellStyleStrategy =
                    new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
//            EasyExcel.write(out, OrderUserCustomExcelDTO.class).sheet("厂商订单列表")
//                    .registerWriteHandler(horizontalCellStyleStrategy).doWrite(voList);

            ExcelWriter excelWriter = EasyExcel.write(bos).withTemplate(templateFileName).build();
            WriteSheet writeSheet = EasyExcel.writerSheet().build();
            //list map 是查询并需导出的数据,并且里面的字段和excel需要导出的字段对应
            // 直接写入Excel数据
            Map<String,Object> map = new HashMap<>();
            //总金额
            map.put("price",totalPrice.stripTrailingZeros().toPlainString());、
            //总笔数
            map.put("total",totalCount);
            //列表数据
            excelWriter.fill(voList, writeSheet);
            excelWriter.fill(map, writeSheet);
            excelWriter.finish();
            bos.flush();

        } catch (Exception e) {
            log.info("列表导出失败!", e);
        } finally {
            out.flush();
            out.close();
        }
    }

到这里功能就结束了,花了一个早上的时间做完的,现学现卖!!! 有问题欢迎在评论区底下留言,看到就会回复!!!