EasyExcel简单合并单元格数据工具类

代码:

java 复制代码
package com.ly.cloud.util;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.write.merge.AbstractMergeStrategy;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author 
 * @Date Created in  2023/12/12 12:44
 * @DESCRIPTION: 合并单元格工具类
 * @Version V1.0
 */

public class CustomMergeStrategyUtil extends AbstractMergeStrategy {

    /**
     * 分组,每几行合并一次
     */
    public List<List<Integer>> mergeColDataGroupCountList;

    /**
     * 目标合并列index
     */
    public List<Integer> targetColumnIndex;
    /**
     * 	需要开始合并单元格的首行index
     */
    public Integer rowIndex;

    /**
     * 	mergeColDataList为待合并目标列的值
     */
    public CustomMergeStrategyUtil(List<List<String>> mergeColDataList, List<Integer> targetColumnIndex) {
        this.mergeColDataGroupCountList = getGroupCountList(mergeColDataList);
        this.targetColumnIndex = targetColumnIndex;
    }


    @Override
    public void merge(Sheet sheet, Cell cell, Head head, Integer relativeRowIndex) {

        if (null == rowIndex) {
            rowIndex = cell.getRowIndex();
        }
        // 仅从首行以及目标列的单元格开始合并,忽略其他
        if (cell.getRowIndex() == rowIndex && targetColumnIndex.contains(cell.getColumnIndex())) {
            //找到对应的需要合并的列
            AtomicInteger i = new AtomicInteger(0);
            Optional<Integer> first = targetColumnIndex.stream().filter(col -> {
                i.getAndIncrement();
                return col == cell.getColumnIndex();
            }).findFirst();
            mergeGroupColumn(sheet, first.get());
        }
    }

    public void mergeGroupColumn(Sheet sheet, Integer index) {
        int rowCount = rowIndex;
        for (Integer count : mergeColDataGroupCountList.get(index)) {
            if (count == 1) {
                rowCount += count;
                continue;
            }
            // 合并单元格
            CellRangeAddress cellRangeAddress = new CellRangeAddress(rowCount, rowCount + count - 1,
                    targetColumnIndex.get(index), targetColumnIndex.get(index));
            sheet.addMergedRegionUnsafe(cellRangeAddress);
            rowCount += count;
        }
    }

    /**
     * 	该方法将目标列根据值是否相同连续可合并,存储可合并的行数
     */
    public List<List<Integer>> getGroupCountList(List<List<String>> exportDataList) {
        if (CollUtil.isEmpty(exportDataList)) {
            return new ArrayList<>();
        }
        List<List<Integer>> groupCountListList = new ArrayList<>();
        exportDataList.forEach(dataList->{
            List<Integer> groupCountList = new ArrayList<>();
            int count = 1;
            for (int i = 1; i < dataList.size(); i++) {
                if (dataList.get(i).equals(dataList.get(i - 1))) {
                    count++;
                } else {
                    groupCountList.add(count);
                    count = 1;
                }
            }
            // 处理完最后一条后
            groupCountList.add(count);
            groupCountListList.add(groupCountList);
        });
        return groupCountListList;
    }
}

使用:

java 复制代码
        List<List<String>> mergeColDataList = Stream.of(pzry.stream().map(PzrtExportDto::getXh).collect(Collectors.toList()),
                    pzry.stream().map(PzrtExportDto::getDwmc).collect(Collectors.toList())).collect(Collectors.toList());
            //第一列(index=0)和第二列(index=1)
            List<Integer> mergeColIndexList = Stream.of(0, 1).collect(Collectors.toList());

            //内部finish的时候会自动关闭流
            EasyExcel.write(response.getOutputStream(), PzrtExportDto.class)

// 这个方法====----------》                    .registerWriteHandler(new CustomMergeStrategyUtil(mergeColDataList, mergeColIndexList))  合并单元格
                    .inMemory(Boolean.TRUE).registerWriteHandler(new CommentWriteHandler())
                    .sheet(FILE_NAME)
                    .doWrite(pzry);
相关推荐
joe02358 小时前
电脑安装 Win10 提示无法在当前分区上安装Windows的解决办法
windows·gpt·电脑·uefi
前端 贾公子9 小时前
vue-cli 模式下安装 uni-ui
前端·javascript·windows
Elastic 中国社区官方博客10 小时前
在 Windows 上使用 Docker 运行 Elastic Open Crawler
大数据·windows·爬虫·elasticsearch·搜索引擎·docker·容器
CIAS13 小时前
clonezilla 导出自动化恢复iso
linux·windows·clonezilla
墨菲安全14 小时前
Node.js Windows下路径遍历漏洞
windows·node.js·路径遍历漏洞
NoirSeeker14 小时前
在windows平台上基于OpenHarmony sdk编译三方库并暴露给ArkTS使用(详细)
c++·windows·arkts·鸿蒙·交叉编译
红藕香残玉簟秋15 小时前
【python学习】windows使用conda管理python虚拟环境
windows·python·conda
紫云无堤20 小时前
20250717 Ubuntu 挂载远程 Windows 服务器上的硬盘
服务器·windows·ubuntu
wydxry1 天前
断网情况下,网线直连 Windows 笔记本 和Ubuntu 服务器
服务器·windows·ubuntu
_Kayo_1 天前
项目学习笔记 display从none切换成block
windows·笔记·学习