当前位置:   article > 正文

利用EasyExcel实现excel模板导出_easyexcel根据模板导出excel

easyexcel根据模板导出excel

1.导入相关依赖

<properties>
    <easyexcel.version>3.1.4</easyexcel.version>
</properties>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>easyexcel</artifactId>
    <version>${easyexcel.version}</version>
    <exclusions>
        <exclusion>
            <artifactId>poi</artifactId>
            <groupId>org.apache.poi</groupId>
        </exclusion>
        <exclusion>
            <artifactId>poi-ooxml</artifactId>
            <groupId>org.apache.poi</groupId>
        </exclusion>
        <exclusion>
            <artifactId>poi-ooxml-schemas</artifactId>
            <groupId>org.apache.poi</groupId>
        </exclusion>
    </exclusions>
</dependency>

2.编辑模板

1.原始模板:

2.编辑模板:

 3.业务代码

serviceImpl实现类:

  1. public void exportExcelSettlement(String settSerialNo, HttpServletResponse response)throws IOException {
  2. //获取模板路径
  3. InputStream template = new PathMatchingResourcePatternResolver().getResource("templates/excel/settlement.xlsx").getInputStream();
  4. if (template.available() == 0) {
  5. log.error("【导出对xx】获取xx模板失败");
  6. throw EXPORT_TEMPLATES_EXCEPTION_SETT;
  7. }
  8. //获取数据
  9. SettlementDetailVO vo = querySettlementDetail(settSerialNo);
  10. List<SettlementDetailGoodsVO> goodsVOS = querySettlementDetailGoods(settSerialNo);
  11. //判断数据是否存在
  12. if (ObjectUtils.isEmpty(vo)) {
  13. log.error("【导出xx】xx信息不存在");
  14. throw SETT_NOT_EXIST_EXCEPTION;
  15. }
  16. if (CollectionUtils.isEmpty(goodsVOS)) {
  17. log.error("【导出xx】xx信息不存在");
  18. throw SETT_NOT_EXIST_EXCEPTION;
  19. }
  20. response.setContentType("application/json;charset=utf-8");
  21. response.setCharacterEncoding("UTF-8");
  22. response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(vo.getBuyersName() + "-" + "对账单" + ".xlsx", "UTF-8"));
  23. //ExcelWriter该对象用于通过POI将值写入Excel
  24. ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).withTemplate(template).build();
  25. //构建excel的sheet
  26. WriteSheet writeSheet = EasyExcel.writerSheet().build();
  27. //控制集合数据垂直填充;ps.集合中的数据需要以FillWrapper()包裹起来才能被解析
  28. FillConfig fillConfig = FillConfig.builder().direction(WriteDirectionEnum.VERTICAL).build();
  29. //表格goods的数据填充
  30. excelWriter.fill(new FillWrapper("goods", goodsVOS), fillConfig, writeSheet);
  31. //其他数据填充
  32. excelWriter.fill(convertObject(vo), writeSheet);
  33. excelWriter.finish();
  34. }
  1. //其余数据的转换
  2. private SettlementDetailVO convertObject(SettlementDetailVO info) {
  3. SettlementDetailVO vo = new SettlementDetailVO();
  4. vo.setSettAmount(info.getSettAmount());
  5. vo.setSettName(info.getSettName());
  6. return vo;
  7. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小小林熬夜学编程/article/detail/590432
推荐阅读
相关标签
  

闽ICP备14008679号