After exporting Excel based on EasyExcel, through simple rule configuration for merging cells, the cell merging effect as shown in the following figure is achieved:
Effect screenshot
The original table data is as follows:
After configuring the cell merging rules, the merged table generated is as follows:
Note: In the third column, no merge rules are configured, and the data remains unchanged.
Custom merge rule class
The following code class is the core class for processing cell merging. It mainly calculates the same data row by row for cell merging.
package com.shanhy.demo.project.service.impl;
import com.alibaba.excel.write.handler.RowWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import com.shanhy.demo.common.utils.JsonUtils;
import com.shanhy.demo.project.vo.ExcelMergeStrategyModel;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.util.CellRangeAddress;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
/**
* Excel 行合并策略
*/
@Slf4j
public class CustomLoopMergeStrategy implements RowWriteHandler {
//上一行
private Row beforeRow = null;
//合并规则(多个)
private List<ExcelMergeStrategyModel> strategyList;
//总行数(不含表头)
private int dataRowTotalSize;
//当前已经处理的行数(不含表头)
private int dataRowCurrentSize = 0;
private CustomLoopMergeStrategy() {
}
/**
* 构造方法
*
* @param loopMergeStrategyJson 合并规则JSON,其中 columnName 为要被自动计算合并的列,relativeColumnNames 表示目标合并列需要参照的相关列(值全部相同则会触发合并目标目标列的单元格)
* 示例:
* String loopMergeStrategyJson =
* [
* {
* "columnName": "A",
* "relativeColumnNames": "A"
* },
* {
* "columnName": "B",
* "relativeColumnNames": "A,B"
* },
* {
* "columnName": "C",
* "relativeColumnNames": "A,B,C"
* },
* {
* "columnName": "D",
* "relativeColumnNames": "A,B,C,D"
* }
* ];
* @param dataRowTotalSize 所有数据的行数
*/
public CustomLoopMergeStrategy(String loopMergeStrategyJson, int dataRowTotalSize) {
//记录excel行数
this.dataRowTotalSize = dataRowTotalSize;
//解析json 获取合并规则
this.strategyList = JsonUtils.jsonToList(loopMergeStrategyJson, ExcelMergeStrategyModel.class);
}
@SneakyThrows
@Override
public void afterRowDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row, Integer relativeRowIndex, Boolean isHead) {
//表头直接跳过
if