当前位置: 首页 > news >正文

使用EasyExcel动态合并单元格(模板方法)

1、导入EasyExcel依赖

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

2、编写实体类

@Data
publci class Student{ @ExcelProperty("姓名")private String name;
}

3、具体方法如下

调用方法(除了基础的模板地址和数据外,增加了合并列索引和分组函数)

/*** 填充模板并合并单元格** @param tempName 模板名称* @param list 填充数据集合* @param resultMap 特殊数据替换map* @param targetFilePath 导出地址* @param excelTypeEnum  ecxcel文件类型* @param mergeColumnIndex sheet中需要合并的列的索引* @param groupFunction    分组函数* @param <T>*/public static <T> void buildMergeExcel(String tempName, List<T> list, Map<String, String> resultMap, String targetFilePath, ExcelTypeEnum excelTypeEnum, int[] mergeColumnIndex, Function<T, String> groupFunction) {try {// 获取模板文件ClassPathResource classPathResource = new ClassPathResource("template/" + tempName);// 行计数,初始值取列头行数int lineCount = 1;// 分别填充list数据和特殊数据ExcelWriter excelWriter = EasyExcel.write(new File(LocalStoragePropertiesConstants.LOCAL_PROFILE + targetFilePath)).excelType(excelTypeEnum).withTemplate(classPathResource.getInputStream()).build();FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();List<CellRangeAddress> rangeCellList = createCellRange(list, mergeColumnIndex, lineCount, groupFunction);WriteSheet writeSheet = EasyExcel.writerSheet().registerWriteHandler(new MergeCellRangeWriteHandler(rangeCellList)).build();excelWriter.fill(list, fillConfig, writeSheet);excelWriter.fill(resultMap, writeSheet);list.clear();excelWriter.finish();} catch (IOException e) {throw new RuntimeException(e);}}

提前计算合并的单元格,在sheet创建后一次性合并

 /*** 生成合并区域** @param detailList       数据列表* @param mergeColumnIndex 要合并的列索引* @param startRowIndex    起始行(含表头时,表头行数)* @param groupFunction    分组函数,如 e -> e.get某字段()* @return 合并区域集合*/public static <T> List<CellRangeAddress> createCellRange(List<T> detailList, int[] mergeColumnIndex, int startRowIndex, Function<T, String> groupFunction) {if (detailList == null || detailList.isEmpty()) {return Collections.emptyList();}// 计算每个key下的数量Map<String, Long> groupMap = new LinkedHashMap<>();for (T item : detailList) {String key = groupFunction.apply(item);groupMap.put(key, groupMap.getOrDefault(key, 0L) + 1);}List<CellRangeAddress> rangeCellList = new ArrayList<>();// 当前行数int lineCount = startRowIndex;for (Map.Entry<String, Long> entry : groupMap.entrySet()) {int count = entry.getValue().intValue();if (count > 1) {int endRowIndex = lineCount + count - 1;for (int columnIndex : mergeColumnIndex) {rangeCellList.add(new CellRangeAddress(lineCount, endRowIndex, columnIndex, columnIndex));}}lineCount += count;}return rangeCellList;}

单元格合并策略

/*** easyExcel 合并单元格*/
public class MergeCellRangeWriteHandler implements SheetWriteHandler {private final List<CellRangeAddress> rangeCellList;public MergeCellRangeWriteHandler(List<CellRangeAddress> rangeCellList) {this.rangeCellList = (rangeCellList == null) ? Collections.emptyList() : rangeCellList;}public void afterSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {Sheet sheet = writeSheetHolder.getSheet();for (CellRangeAddress cellRangeAddress : this.rangeCellList) {sheet.addMergedRegionUnsafe(cellRangeAddress);}}
}

调用如下:

        String sheetTitle = "模板名称";FileResultVO fileResultVO = ExpandFileUtil.generateFilePath(EXTENSION_XLSX, sheetTitle + UUID.randomUUID(), EXTENSION_XLSX);ExpandEasyExcelUtil.buildMergeExcel("MB.xlsx",dataList, null, fileResultVO.getFilePath(),ExcelTypeEnum.XLSX,new int[]{0, 1, 2, 3, 4},Student::getName);

工作中实测使用,有什么问题欢迎留言交流

http://www.dtcms.com/a/272748.html

相关文章:

  • RK3568项目(八)--linux驱动开发之基础外设(上)
  • 亚马逊运营中出单词反查
  • 机器学习:反向神经元传播公式推导
  • 记录今天学习Comfyui的感受
  • python正则表达式(小白五分钟从入门到精通)
  • 智能化时代下的门店运营:AI的深刻影响
  • 2025年第十五届APMCM亚太地区大学生数学建模竞赛(中文赛项)
  • 【C++】红黑树的底层思想 and 大厂面试常问
  • BootStrap
  • 售前:该站高位思考还是站低位思考
  • Codeforces Round 1034 (Div. 3) G题题解记录
  • 创建本地软件仓库(rhel7与rhel9)
  • HighReport报表工具开始支持BS报表设计器
  • SW-CA(多平台产品上架系统)
  • uni-app 途径站点组件开发与实现分享
  • 体积超过2MB?uniapp小程序分包上传
  • [论文阅读]Text Compression for Efficient Language Generation
  • Go语言包管理完全指南:从基础到最佳实践
  • BM12 单链表的排序
  • 东土科技智能塔机系统亮相南京,助力智能建造高质量发展
  • HOOK专题
  • web前端面试笔记
  • 北京一家IPO业绩持续性存疑,关联交易频繁独立性堪忧
  • 24、企业设备清单管理(Equipment)详解:从分类到管理,设备全生命周期把控
  • etf期权到期的风险大不大怎么看?
  • MySQL中使用GROUP_CONCAT数据丢失问题的原因和处理方案
  • 深入理解区块链 | 去中心化架构与密码学保障
  • springboot数据脱敏(接口级别)
  • Uni-app 生命周期与钩子:程序的“生命”旅程
  • 企业电商平台搭建:ZKmall开源商城服务器部署与容灾方案