当前位置:   article > 正文

java使用easyexcel+poi实现excel模板多sheet页导出

java使用easyexcel+poi实现excel模板多sheet页导出

         使用easyexcel+poi实现excel模板,动态sheet页导出需求。

一、使用的依赖

  1. <dependency>
  2. <groupId>com.alibaba</groupId>
  3. <artifactId>easyexcel</artifactId>
  4. <version>3.3.1</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>cn.hutool</groupId>
  8. <artifactId>hutool-all</artifactId>
  9. <version>5.8.0</version>
  10. </dependency>

二、需求

        sheet0页需求是导出的数据为固定的样式。sheet1页的需求是导出多条数据。基于此需求,考虑的是用easyexcel模版导出的方式实现此需求较为简单。

sheet0页样式

sheet1页样式

 三、模版的设计

easyexcel官方文档

 四、问题点

         在多公司的情况下,第二页需要动态多sheet页,比如两个公司的就需要两个sheet1页,并导出每个公司下的人员详情。因为easyexcel不支持动态sheet页,要是重写导出又比较复杂,综合考虑使用poi+easyexcel一起实现多公司的导出。

 五、功能的实现

        导出模版在项目中的位置

导出excel实例代码

  1. import cn.hutool.core.io.resource.ClassPathResource;
  2. import cn.hutool.core.util.NumberUtil;
  3. import com.alibaba.excel.EasyExcel;
  4. import com.alibaba.excel.ExcelWriter;
  5. import com.alibaba.excel.util.MapUtils;
  6. import com.alibaba.excel.write.metadata.WriteSheet;
  7. import com.alibaba.excel.write.metadata.fill.FillConfig;
  8. import com.alibaba.fastjson2.JSON;
  9. import lombok.extern.slf4j.Slf4j;
  10. import org.apache.poi.xssf.usermodel.XSSFWorkbook;
  11. import org.springframework.web.bind.annotation.PostMapping;
  12. import org.springframework.web.bind.annotation.RequestMapping;
  13. import org.springframework.web.bind.annotation.RestController;
  14. import javax.servlet.http.HttpServletRequest;
  15. import javax.servlet.http.HttpServletResponse;
  16. import java.io.*;
  17. import java.math.BigDecimal;
  18. import java.net.URLEncoder;
  19. import java.util.ArrayList;
  20. import java.util.HashMap;
  21. import java.util.List;
  22. import java.util.Map;
  23. /**
  24. * @author 小红花
  25. * @version 1.0
  26. * @date 2023/12/28
  27. * @description mytest
  28. */
  29. @RestController
  30. @RequestMapping("test")
  31. @Slf4j
  32. public class MyTestController {
  33. @PostMapping(value = "export")
  34. public void exportExcel(HttpServletRequest request, HttpServletResponse response) throws IOException {
  35. long startTime = System.currentTimeMillis();
  36. System.out.println("导出开始时间:" + startTime + "ms");
  37. //设置输出流格式以及文件名:
  38. response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
  39. response.setCharacterEncoding("utf-8");
  40. String fileName = URLEncoder.encode("计提表-导出", "UTF-8");
  41. response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
  42. ExcelWriter excelWriter = null;
  43. InputStream stream = null;
  44. ByteArrayOutputStream baos = null;
  45. try {
  46. //1.找出模板文件,并转化为输入流;
  47. ClassPathResource classPathResource = new ClassPathResource("export/test/jitinew.xlsx");
  48. stream = classPathResource.getStream();
  49. baos = new ByteArrayOutputStream();
  50. OutputStream outputStream = response.getOutputStream();
  51. //2.数据准备
  52. //sheet0页数据
  53. Map<String, Object> sheet0Data = new HashMap<>();
  54. sheet0Data.put("deptName", "测试部门");
  55. sheet0Data.put("settlementCycle", "2023-12");
  56. sheet0Data.put("contractName", "测试合同名称");
  57. sheet0Data.put("contractNum", "12345678");
  58. sheet0Data.put("predictMoneyWithoutRate", "20000.00");
  59. sheet0Data.put("predictMoney", "21000.00");
  60. sheet0Data.put("attendanceDays", "21");
  61. sheet0Data.put("companyNames", "测试供应商");
  62. //动态sheet页数据
  63. List<Map<String, Object>> sheet1Data = new ArrayList<>();
  64. for (int i = 0; i < 2; i++) {
  65. BigDecimal serveDaysAll = BigDecimal.ZERO;
  66. BigDecimal usrServicePriceAll = BigDecimal.ZERO;
  67. BigDecimal coefficientAssessPriceAll = BigDecimal.ZERO;
  68. BigDecimal predictPriceWithoutRateAll = BigDecimal.ZERO;
  69. BigDecimal predictPriceAll = BigDecimal.ZERO;
  70. //准备sheet1页集合数据
  71. List<Map<String, Object>> sheetListData = new ArrayList<>();
  72. for (int j = 0; j < 5; j++) {
  73. Map<String, Object> sheetList = new HashMap<>();
  74. BigDecimal serveDays = new BigDecimal(21);
  75. BigDecimal usrServicePrice = new BigDecimal(10000);
  76. BigDecimal coefficientAssessPrice = new BigDecimal(20000);
  77. BigDecimal predictPriceWithoutRate = new BigDecimal(30000);
  78. BigDecimal predictPrice = new BigDecimal(31000);
  79. sheetList.put("month", "2023-12");
  80. sheetList.put("realName", "测试人员" + i + j);
  81. sheetList.put("personNum", "1000" + i + j);
  82. sheetList.put("deptName", "测试部门");
  83. sheetList.put("projName", "测试项目");
  84. sheetList.put("serveName", "测试");
  85. sheetList.put("levelName", "中级");
  86. sheetList.put("serveDays", serveDays);
  87. sheetList.put("usrServicePrice", usrServicePrice);
  88. sheetList.put("coefficientAssessPrice", coefficientAssessPrice);
  89. sheetList.put("predictPriceWithoutRate", predictPriceWithoutRate);
  90. sheetList.put("predictPrice", predictPrice);
  91. serveDaysAll = NumberUtil.add(serveDaysAll, serveDays);
  92. usrServicePriceAll = NumberUtil.add(usrServicePriceAll, usrServicePrice);
  93. coefficientAssessPriceAll = NumberUtil.add(coefficientAssessPriceAll, coefficientAssessPrice);
  94. predictPriceWithoutRateAll = NumberUtil.add(predictPriceWithoutRateAll, predictPriceWithoutRate);
  95. predictPriceAll = NumberUtil.add(predictPriceAll, predictPrice);
  96. sheetListData.add(sheetList);
  97. }
  98. //准备sheet1页基础数据
  99. Map<String, Object> sheet1Map = new HashMap<>();
  100. sheet1Map.put("title", "测试sheet" + i);
  101. sheet1Map.put("companyName", "测试公司" + i);
  102. sheet1Map.put("deptName", "2023-12");
  103. sheet1Map.put("serveDaysAll", serveDaysAll);
  104. sheet1Map.put("usrServicePriceAll", usrServicePriceAll);
  105. sheet1Map.put("coefficientAssessPriceAll", coefficientAssessPriceAll);
  106. sheet1Map.put("predictPriceWithoutRateAll", predictPriceWithoutRateAll);
  107. sheet1Map.put("predictPriceAll", predictPriceAll);
  108. sheet1Map.put("sheetListData", sheetListData);
  109. sheet1Data.add(sheet1Map);
  110. }
  111. //3.根据sheet1集合长度,复制模版sheet1页
  112. XSSFWorkbook workbook = new XSSFWorkbook(stream);
  113. for (int i = 1; i < sheet1Data.size(); i++) {
  114. //开始复制sheet1页 ,新的sheet以sheet2开始。(复制sheet页名字不可重复)
  115. workbook.cloneSheet(1, "sheet" + (i + 1));
  116. }
  117. //把workbook写到流里
  118. workbook.write(baos);
  119. byte[] bytes = baos.toByteArray();
  120. stream = new ByteArrayInputStream(bytes);
  121. excelWriter = EasyExcel.write(outputStream).withTemplate(stream).build();
  122. //4.填充模版数据
  123. //写入sheet0
  124. WriteSheet sheetDataWrite = EasyExcel.writerSheet(0).build();
  125. excelWriter.fill(sheet0Data, sheetDataWrite);
  126. //写入动态sheet页基础数据
  127. for (int i = 0; i < sheet1Data.size(); i++) {
  128. //获取sheeti写入对象
  129. sheetDataWrite = EasyExcel.writerSheet(i + 1).build();
  130. //获取数据
  131. Map<String, Object> sheet1Map = sheet1Data.get(i);
  132. List<Map<String, Object>> sheetListData = (List<Map<String, Object>>) sheet1Map.get("sheetListData");
  133. //写入excel
  134. FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
  135. excelWriter.fill(sheetListData, fillConfig, sheetDataWrite);
  136. excelWriter.fill(sheet1Map, sheetDataWrite);
  137. }
  138. } catch (Exception e) {
  139. e.printStackTrace();
  140. // 重置response
  141. response.reset();
  142. response.setContentType("application/json");
  143. response.setCharacterEncoding("utf-8");
  144. Map<String, Object> map = MapUtils.newHashMap();
  145. map.put("code", 500);
  146. map.put("message", "下载文件失败:" + e.getMessage());
  147. response.getWriter().println(JSON.toJSONString(map));
  148. } finally {
  149. //关流
  150. if (excelWriter != null) {
  151. excelWriter.finish();
  152. }
  153. if (baos != null) {
  154. baos.close();
  155. }
  156. if (stream != null) {
  157. stream.close();
  158. }
  159. }
  160. long endTime = System.currentTimeMillis();
  161. System.out.println("导出结束时间:" + endTime + "ms");
  162. System.out.println("导出所用时间:" + (endTime - startTime) / 1000 + "秒");
  163. }
  164. }

 实现效果如图

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

闽ICP备14008679号