EasyExcel 动态合并列
时间:2024-5-15 16:18 作者:紫琪软件工作室 分类: 工具集
package com.ksec.eicp.crmc.listener.easyexcel;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.write.handler.AbstractRowWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress;
/*
- 自定义合并列策略
- @version V1.0
- @author zhang ji
-
@ date 2020-09-15 9:29
**/
@Getter
@Setter
@ToString
public class DefaultMergeRowStrategy extends AbstractRowWriteHandler {/**
- 合并比对起始行值
*/
private String defaultValue;
/** - 合并目标列索引
*/
private Integer cellIndex;
/** - 数据开始行索引
*/
private Integer dataBeginRowIndex;
/** - 当前导出数据长度
*/
private Integer dataLength;
/** - 开始行索引
*/
private Integer mergeBeginRowIndex;
public DefaultMergeRowStrategy(String defaultValue, Integer cellIndex, Integer dataBeginRowIndex, Integer dataLength) {
this.defaultValue = defaultValue;
this.cellIndex = cellIndex;
this.dataBeginRowIndex = dataBeginRowIndex;
this.dataLength = dataLength;
}@Override
public void afterRowDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row,
Integer relativeRowIndex, Boolean isHead) {
if (isHead) {
return;
}String cellValueStr = StrUtil.isNotBlank(row.getCell(cellIndex).getStringCellValue())? row.getCell(cellIndex).getStringCellValue():""; //遇到不一致的值,前面进行合并 if(!cellValueStr.equals(defaultValue)) { this.mergeRow(writeSheetHolder.getSheet(), null != this.mergeBeginRowIndex?this.mergeBeginRowIndex:this.dataBeginRowIndex, row.getRowNum() - 1, this.cellIndex, this.cellIndex); this.mergeBeginRowIndex = row.getRowNum() + (this.dataLength == relativeRowIndex + 1?1:0); this.defaultValue = cellValueStr; } else { //判断是否是最后一组记录,最后一组记录不会进入上方判断逻辑,故需单独处理合并 if(this.dataLength == relativeRowIndex + 1) { //一条记录不进行合并 if(((null != this.mergeBeginRowIndex?this.mergeBeginRowIndex:this.dataBeginRowIndex)) != row.getRowNum()) { this.mergeRow(writeSheetHolder.getSheet(), null != this.mergeBeginRowIndex?this.mergeBeginRowIndex:this.dataBeginRowIndex, row.getRowNum(), this.cellIndex, this.cellIndex); } this.mergeBeginRowIndex = row.getRowNum() + 1; this.defaultValue = ""; } }
}
private void mergeRow(Sheet sheet, int firstRow, int lastRow, int firstCol, int lastCol) {
CellRangeAddress cellRangeAddress = new CellRangeAddress(firstRow, lastRow, firstCol, lastCol);
sheet.addMergedRegionUnsafe(cellRangeAddress);
} - 合并比对起始行值
}