当前位置:   article > 正文

EasyExcel模板导出(行和列自动合并)_easyexcel 模板导出

easyexcel 模板导出

目录

1.需求背景:

2.初步实现:

3.列合并

4.行合并

5.excel字体样式内容居中

6.将三个工具类初始化后注册后最终代码:


1.需求背景:

①需要从第三方获取数据,第三方接口有两个参数,开始时间和结束时间

②获取回来的数据并没有入库,所以不能通过数据库将数据归类统计,excel合并大概的流程是判断上一行或者左右相邻列是否相同,然后进行合并,所以不能是零散的数据且客户要求每一个自治区和每一个航站要统计总数(后续会出一个数据整合文章),咱们默认数据已经整理好了.效果如下:

③最终效果:

2.初步实现:

①利用easyExcel模板填充,实现效果如下图

代码:

  1. //模板位置
  2. InputStream template = new PathMatchingResourcePatternResolver()
  3. .getResource("templates/飞机扑救火场统计表.xlsx").getInputStream();
  4. response.setContentType("application/octet-stream");
  5. response.setCharacterEncoding("utf-8");
  6. // 这里URLEncoder.encode可以防止中文乱码
  7. response.setHeader("Content-Disposition",
  8. "attachment;filename=" + java.net.URLEncoder.encode("飞机扑救火场统计表.xlsx", "UTF-8"));
  9. //ExcelWriter该对象用于通过POI将值写入Excel
  10. ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).withTemplate(template).build();
  11. //构建excel的sheet
  12. WriteSheet writeSheet = EasyExcel.writerSheet().build();
  13. Map<String, String> fileData = new HashMap<>();
  14. fileData.put("beginDate", beginDate);
  15. fileData.put("endDate", endDate);
  16. excelWriter.fill(list, writeSheet);
  17. excelWriter.fill(fileData, writeSheet);
  18. excelWriter.finish();

模板:

3.列合并

 列合并工具类,合并代码在afterCellDispose这个方法中,不管是列合并还是行合并其实是重写这个方法,将你的合并逻辑写在里面就可以.

  1. //列合并工具类
  2. public class ExcelFillCellMergePrevColUtils implements CellWriteHandler {
  3. private static final String KEY ="%s-%s";
  4. //所有的合并信息都存在了这个map里面
  5. Map<String, Integer> mergeInfo = new HashMap<>();
  6. public ExcelFillCellMergePrevColUtils() {
  7. }
  8. @Override
  9. public void beforeCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row, Head head, Integer integer, Integer integer1, Boolean aBoolean) {
  10. }
  11. @Override
  12. public void afterCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Cell cell, Head head, Integer integer, Boolean aBoolean) {
  13. }
  14. @Override
  15. public void afterCellDataConverted(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, CellData cellData, Cell cell, Head head, Integer integer, Boolean aBoolean) {
  16. }
  17. @Override
  18. public void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, List<CellData> list, Cell cell, Head head, Integer integer, Boolean aBoolean) {
  19. //当前行
  20. int curRowIndex = cell.getRowIndex();
  21. //当前列
  22. int curColIndex = cell.getColumnIndex();
  23. Integer num = mergeInfo.get(String.format(KEY, curRowIndex, curColIndex));
  24. if(null != num){
  25. // 合并最后一行 ,列
  26. mergeWithPrevCol(writeSheetHolder, cell, curRowIndex, curColIndex,num);
  27. }
  28. }
  29. public void mergeWithPrevCol(WriteSheetHolder writeSheetHolder, Cell cell, int curRowIndex, int curColIndex, int num) {
  30. Sheet sheet = writeSheetHolder.getSheet();
  31. CellRangeAddress cellRangeAddress = new CellRangeAddress(curRowIndex, curRowIndex, curColIndex, curColIndex + num);
  32. sheet.addMergedRegion(cellRangeAddress);
  33. }
  34. //num从第几列开始增加多少列,(6,2,7)代表的意思就是第6行的第2列至第2+7也就是9列开始合并
  35. public void add (int curRowIndex, int curColIndex , int num){
  36. mergeInfo.put(String.format(KEY, curRowIndex, curColIndex),num);
  37. }
  38. }

可以参考下面的这个excel看一下,广西壮族自治区的航站合计是从第8行,第2列开始+2列的范围合并

列合并效果图:

4.行合并

行合并工具类初级版本: 

报错位置:ExcelFillCellMergeStrategyUtils合并策略类的 mergeWithPrevRow()方法中

这一行代码会报空指针异常 java.lang.NullPointerException

Row preRow = cell.getSheet().getRow(curRowIndex - 1);

 

原因:

debug发现,cell.getSheet() 行的下标第0到42的数据行,获取的是同一个 sheet 实例

当下标为43时,执行cell.getSheet()获取到的 sheet 实例不一样

而下标0到42的行数据被存储到 存储sheet中。如果上一行为空则去缓存中获取上一行,

writeSheetHolder.getCachedSheet()
  1. Row preRow = cell.getSheet().getRow(curRowIndex - 1);
  2. if (preRow == null) {
  3. // 当获取不到上一行数据时,使用缓存sheet中数据
  4. preRow = writeSheetHolder.getCachedSheet().getRow(curRowIndex - 1);
  5. }
  6. Cell preCell=preRow.getCell(curColIndex);

行合并工具类最终版:

  1. public class ExcelFillCellMergeStrategyUtils implements CellWriteHandler {
  2. /**
  3. * 合并字段的下标
  4. */
  5. private int[] mergeColumnIndex;
  6. /**
  7. * 合并几行
  8. */
  9. private int mergeRowIndex;
  10. public ExcelFillCellMergeStrategyUtils(int mergeRowIndex, int[] mergeColumnIndex) {
  11. this.mergeRowIndex = mergeRowIndex;
  12. this.mergeColumnIndex = mergeColumnIndex;
  13. }
  14. @Override
  15. public void beforeCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row,
  16. Head head, Integer integer, Integer integer1, Boolean aBoolean) {
  17. }
  18. @Override
  19. public void afterCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Cell cell,
  20. Head head, Integer integer, Boolean aBoolean) {
  21. }
  22. @Override
  23. public void afterCellDataConverted(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder,
  24. CellData cellData, Cell cell, Head head, Integer integer, Boolean aBoolean) {
  25. }
  26. @Override
  27. public void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder,
  28. List<CellData> list, Cell cell, Head head, Integer integer, Boolean aBoolean) {
  29. //当前行
  30. int curRowIndex = cell.getRowIndex();
  31. //当前列
  32. int curColIndex = cell.getColumnIndex();
  33. if (curRowIndex > mergeRowIndex) {
  34. for (int i = 0; i < mergeColumnIndex.length; i++) {
  35. if (curColIndex == mergeColumnIndex[i]) {
  36. mergeWithPrevRow(writeSheetHolder, cell, curRowIndex, curColIndex);
  37. break;
  38. }
  39. }
  40. }
  41. }
  42. private void mergeWithPrevRow(WriteSheetHolder writeSheetHolder, Cell cell, int curRowIndex, int curColIndex) {
  43. //获取当前行的当前列的数据和上一行的当前列列数据,通过上一行数据是否相同进行合并
  44. Object curData = cell.getCellTypeEnum() == CellType.STRING ? cell.getStringCellValue() :
  45. cell.getNumericCellValue();
  46. Row preRow = cell.getSheet().getRow(curRowIndex - 1);
  47. if (preRow == null) {
  48. // 当获取不到上一行数据时,使用缓存sheet中数据
  49. preRow = writeSheetHolder.getCachedSheet().getRow(curRowIndex - 1);
  50. }
  51. Cell preCell=preRow.getCell(curColIndex);
  52. Object preData = preCell.getCellTypeEnum() == CellType.STRING ? preCell.getStringCellValue() :
  53. preCell.getNumericCellValue();
  54. // 比较当前行的第一列的单元格与上一行是否相同,相同合并当前单元格与上一行
  55. if (curData.equals(preData)) {
  56. Sheet sheet = writeSheetHolder.getSheet();
  57. List<CellRangeAddress> mergeRegions = sheet.getMergedRegions();
  58. boolean isMerged = false;
  59. for (int i = 0; i < mergeRegions.size() && !isMerged; i++) {
  60. CellRangeAddress cellRangeAddr = mergeRegions.get(i);
  61. // 若上一个单元格已经被合并,则先移出原有的合并单元,再重新添加合并单元
  62. if (cellRangeAddr.isInRange(curRowIndex - 1, curColIndex)) {
  63. sheet.removeMergedRegion(i);
  64. cellRangeAddr.setLastRow(curRowIndex);
  65. sheet.addMergedRegion(cellRangeAddr);
  66. isMerged = true;
  67. }
  68. }
  69. // 若上一个单元格未被合并,则新增合并单元
  70. if (!isMerged) {
  71. CellRangeAddress cellRangeAddress = new CellRangeAddress(curRowIndex - 1, curRowIndex, curColIndex,
  72. curColIndex);
  73. sheet.addMergedRegion(cellRangeAddress);
  74. }
  75. }
  76. }
  77. }

5.excel字体样式内容居中

样式工具类: 

  1. public class CellStyleStrategy extends AbstractCellStyleStrategy {
  2. private WriteCellStyle headWriteCellStyle;
  3. private List<WriteCellStyle> contentWriteCellStyleList;
  4. private CellStyle headCellStyle;
  5. private List<CellStyle> contentCellStyleList;
  6. public CellStyleStrategy(WriteCellStyle headWriteCellStyle,
  7. List<WriteCellStyle> contentWriteCellStyleList) {
  8. this.headWriteCellStyle = headWriteCellStyle;
  9. this.contentWriteCellStyleList = contentWriteCellStyleList;
  10. }
  11. public CellStyleStrategy(WriteCellStyle headWriteCellStyle, WriteCellStyle contentWriteCellStyle) {
  12. this.headWriteCellStyle = headWriteCellStyle;
  13. contentWriteCellStyleList = new ArrayList<WriteCellStyle>();
  14. contentWriteCellStyleList.add(contentWriteCellStyle);
  15. }
  16. @Override
  17. protected void initCellStyle(Workbook workbook) {
  18. if (headWriteCellStyle != null) {
  19. headCellStyle = StyleUtil.buildHeadCellStyle(workbook, headWriteCellStyle);
  20. }
  21. if (contentWriteCellStyleList != null && !contentWriteCellStyleList.isEmpty()) {
  22. contentCellStyleList = new ArrayList<CellStyle>();
  23. for (WriteCellStyle writeCellStyle : contentWriteCellStyleList) {
  24. contentCellStyleList.add(StyleUtil.buildContentCellStyle(workbook, writeCellStyle));
  25. }
  26. }
  27. }
  28. @Override
  29. protected void setHeadCellStyle(Cell cell, Head head, Integer relativeRowIndex) {
  30. if (headCellStyle == null) {
  31. return;
  32. }
  33. cell.setCellStyle(headCellStyle);
  34. }
  35. @Override
  36. protected void setContentCellStyle(Cell cell, Head head, Integer relativeRowIndex) {
  37. if (contentCellStyleList == null || contentCellStyleList.isEmpty()) {
  38. return;
  39. }
  40. cell.setCellStyle(contentCellStyleList.get(0));
  41. }
  42. }
  1. public CellStyleStrategy horizontalCellStyleStrategyBuilder() {
  2. WriteCellStyle headWriteCellStyle = new WriteCellStyle();
  3. //设置头字体
  4. WriteFont headWriteFont = new WriteFont();
  5. headWriteFont.setFontHeightInPoints((short) 13);
  6. headWriteFont.setBold(true);
  7. headWriteCellStyle.setWriteFont(headWriteFont);
  8. //设置头居中
  9. headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
  10. //内容策略
  11. WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
  12. //设置 水平居中
  13. contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
  14. //垂直居中
  15. contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
  16. return new CellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
  17. }

6.将三个工具类初始化后注册后最终代码:

  1. public void exportExcel(HttpServletResponse response, String beginDate, String endDate) throws IOException {
  2. ExcelFillCellMergePrevColUtils excelFillCellMergePrevColUtils = new ExcelFillCellMergePrevColUtils();
  3. String terminalTotal = "航站合计";
  4. String provinceTotal = "省区合计";
  5. Map<String, ProvinceInfo> map = handlePlaneDownFire(beginDate, endDate);
  6. List<PlaneDownFire> list = new ArrayList<>();
  7. map.forEach((k, v) -> {
  8. //添加航站合计
  9. v.getTerminalInfos().forEach((k1, v1) -> {
  10. list.addAll(v1.getList());
  11. int size = list.size();
  12. excelFillCellMergePrevColUtils.add(size + 3, 2, 2);
  13. CommissionInfo terminalCommissionInfoTotal = v1.getSum();
  14. PlaneDownFire planeDownFire = CommissionInfoConvert.INSTANCE.commissionInfo2planeDownFire(terminalCommissionInfoTotal);
  15. planeDownFire.setProvincialArea(v.getName())
  16. .setMachineNumber(String.valueOf(size))
  17. .setFlyingCommission(String.valueOf(size))
  18. .setTerminal(v1.getName())
  19. .setModel(terminalTotal);
  20. list.add(planeDownFire);
  21. });
  22. int size = list.size();
  23. excelFillCellMergePrevColUtils.add(size + 3, 1, 3);
  24. //省区合计
  25. CommissionInfo provinceCommissionInfoTotal = v.getSum();
  26. PlaneDownFire planeDownFire = CommissionInfoConvert.INSTANCE.commissionInfo2planeDownFire(provinceCommissionInfoTotal);
  27. planeDownFire.setProvincialArea(v.getName())
  28. .setTerminal(provinceTotal)
  29. .setModel(String.valueOf(size));
  30. list.add(planeDownFire);
  31. });
  32. //设置第几列开始合并
  33. int[] mergeColumnIndex = {0, 1, 2, 3};
  34. //设置第几行开始合并
  35. int mergeRowIndex = 3;
  36. ExcelFillCellMergeStrategyUtils excelFillCellMergeStrategyUtils = new ExcelFillCellMergeStrategyUtils(mergeRowIndex, mergeColumnIndex);
  37. InputStream template = new PathMatchingResourcePatternResolver().getResource("templates/飞机扑救火场统计表.xlsx").getInputStream();
  38. response.setContentType("application/octet-stream");
  39. response.setCharacterEncoding("utf-8");
  40. // 这里URLEncoder.encode可以防止中文乱码
  41. response.setHeader("Content-Disposition",
  42. "attachment;filename=" + java.net.URLEncoder.encode("飞机扑救火场统计表.xlsx", "UTF-8"));
  43. //ExcelWriter该对象用于通过POI将值写入Excel
  44. ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).withTemplate(template)
  45. //样式注册
  46. .registerWriteHandler(horizontalCellStyleStrategyBuilder())
  47. //行注册
  48. .registerWriteHandler(excelFillCellMergeStrategyUtils)
  49. //列注册
  50. .registerWriteHandler(excelFillCellMergePrevColUtils)
  51. .build();
  52. //构建excel的sheet
  53. WriteSheet writeSheet = EasyExcel.writerSheet().build();
  54. Map<String, String> fileData = new HashMap<>();
  55. fileData.put("beginDate", beginDate);
  56. fileData.put("endDate", endDate);
  57. excelWriter.fill(fileData, writeSheet);
  58. excelWriter.fill(list, writeSheet);
  59. excelWriter.finish();
  60. }

总结:EasyExcel动态导出几乎能够满足大部分需求,说到底还是实现CellWriteHandler 类里面的

afterCellDispose方法,里面实现你想要的效果.
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/590495
推荐阅读
  

闽ICP备14008679号