!480 优化单元格合并后多余内容的清除

* excel插件 优化合并策略 在合适的生命周期完成合并 去除被合并单元格的非首行内容
This commit is contained in:
司猫子 2024-02-04 01:52:19 +00:00 committed by 疯狂的狮子Li
parent 70bf1a48d0
commit 55ce0e34c9

View File

@ -5,6 +5,8 @@ import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.annotation.ExcelProperty; import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.metadata.Head; import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.write.handler.WorkbookWriteHandler;
import com.alibaba.excel.write.handler.context.WorkbookWriteHandlerContext;
import com.alibaba.excel.write.merge.AbstractMergeStrategy; import com.alibaba.excel.write.merge.AbstractMergeStrategy;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.Data; import lombok.Data;
@ -25,7 +27,7 @@ import java.util.*;
* @author Lion Li * @author Lion Li
*/ */
@Slf4j @Slf4j
public class CellMergeStrategy extends AbstractMergeStrategy { public class CellMergeStrategy extends AbstractMergeStrategy implements WorkbookWriteHandler {
private final List<CellRangeAddress> cellList; private final List<CellRangeAddress> cellList;
private final boolean hasTitle; private final boolean hasTitle;
@ -40,17 +42,28 @@ public class CellMergeStrategy extends AbstractMergeStrategy {
@Override @Override
protected void merge(Sheet sheet, Cell cell, Head head, Integer relativeRowIndex) { protected void merge(Sheet sheet, Cell cell, Head head, Integer relativeRowIndex) {
// judge the list is not null //单元格写入了,遍历合并区域,如果该Cell在区域内,但非首行,则清空
if (CollUtil.isNotEmpty(cellList)) { final int rowIndex = cell.getRowIndex();
// the judge is necessary if (CollUtil.isNotEmpty(cellList)){
if (cell.getRowIndex() == rowIndex && cell.getColumnIndex() == 0) { for (CellRangeAddress cellAddresses : cellList) {
for (CellRangeAddress item : cellList) { final int firstRow = cellAddresses.getFirstRow();
sheet.addMergedRegion(item); if (cellAddresses.isInRange(cell) && rowIndex != firstRow){
cell.setBlank();
} }
} }
} }
} }
@Override
public void afterWorkbookDispose(final WorkbookWriteHandlerContext context) {
//当前表格写完后统一写入
if (CollUtil.isNotEmpty(cellList)){
for (CellRangeAddress item : cellList) {
context.getWriteContext().writeSheetHolder().getSheet().addMergedRegion(item);
}
}
}
@SneakyThrows @SneakyThrows
private List<CellRangeAddress> handle(List<?> list, boolean hasTitle) { private List<CellRangeAddress> handle(List<?> list, boolean hasTitle) {
List<CellRangeAddress> cellList = new ArrayList<>(); List<CellRangeAddress> cellList = new ArrayList<>();