百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术文章 > 正文

EasyExcel自定义合并单元格多行合并根据自定义字段

zhezhongyun 2025-03-20 21:00 8 浏览

第一种方式实现

通过定义注解+实现RowWriteHandler接口中的afterRowDispose方法来动态合并行根据指定的key可以是单个字段也可以是多个字段也可以根据注解指定。注解方式使用参考原作者。

1 自定义注解

package com.test.utils;
 
import java.lang.annotation.*;
 
/**
 * 自定义注解,用于判断是否需要合并以及合并的主键
 *
 */
@Documented
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface CustomMerge {
 
    /**
     * 是否是主键,即该字段相同的行合并
     */
    boolean isPk() default false;
 
    /**
     * 需要合并单元格字段标识、标识一致的会分为同一组
     */
    String[] value();
}
 

2 策略类

package com.test.utils;

import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.write.handler.RowWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress;

import java.lang.reflect.Field;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 自定义单元格合并策略
 *
 */
public class CustomMergeStrategy implements RowWriteHandler {
    /**
     * 主键下标集合
     */
    private Map<String, List> pkColumnIndexMap = new LinkedHashMap<>();

    /**
     * 需要合并的列的下标集合
     */
    private Map<String, List> mergeValueColumnIndexMap = new LinkedHashMap<>();

    /**
     * 需要合并的列
     */
    private final Map cellRangeAddressMap = new HashMap<>();

    /**
     * 去重后的主键下标集合
     */
    private final Set pkColumnIndexSet = new HashSet<>();

    /**
     * sheet数据总行数
     */
    private final int totalDataRowCount;

    /**
     * DTO数据类型
     */
    private final Class elementType;
   // 增加自定义合并key如果自定义合并key为空按照原有策略走
    private int[] mergeIndexs;

    public CustomMergeStrategy(Class elementType, int totalDataRowCount, int[] mergeIndexs) {
        this.elementType = elementType;
        this.totalDataRowCount = totalDataRowCount;
        this.mergeIndexs = mergeIndexs;
    }

    @Override
    public void afterRowDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row, Integer relativeRowIndex, Boolean isHead) {
        // 如果是标题,则直接返回
        if (isHead) {
            return;
        }

        // 获取当前sheet
        Sheet sheet = writeSheetHolder.getSheet();

        if (pkColumnIndexMap.isEmpty()) {
            this.lazyInit();
        }

        // 判断是否需要和上一行进行合并,不能和标题合并,只能数据行之间合并
        if (row.getRowNum() <= 1 return row lastrow='sheet.getRow(row.getRowNum()' - 1 pkcolumnindexmap.foreachk v -> {
            // 将本行和上一行是同一类型的数据(通过主键字段进行判断),则需要合并
            boolean mergeBol = true;
            for (Integer pkIndex : v) {
                if (lastRow.getCell(pkIndex) == null || row.getCell(pkIndex) == null) {
                    continue;
                }
                String lastKey = null;
                String currentKey = null;
                if (ObjectUtils.isEmpty(mergeIndexs)) {
                    lastKey = getStringCellValue(lastRow.getCell(pkIndex));
                    currentKey = getStringCellValue(row.getCell(pkIndex));

                } else {
                    lastKey = Arrays.stream(mergeIndexs).mapToObj(index -> getStringCellValue(lastRow.getCell(index))).collect(Collectors.joining());
                    currentKey = Arrays.stream(mergeIndexs).mapToObj(index -> getStringCellValue(row.getCell(index))).collect(Collectors.joining());
                }

                if (!StringUtils.equalsIgnoreCase(lastKey, currentKey)) {
                    mergeBol = false;
                    break;
                }
            }
            List mergeValueColumnIndex = mergeValueColumnIndexMap.get(k);
            if (mergeBol) {
                // 如果需要合并,则处理合并逻辑
                for (Integer needMerIndex : mergeValueColumnIndex) {
                    String key = String.format("%s-%s", k, needMerIndex);
                    // 处理已存在合并范围的情况,避免重复合并
                    if (pkColumnIndexSet.contains(needMerIndex)) {
                        long count = cellRangeAddressMap.entrySet().stream().filter(entry -> entry.getKey().contains("-" + needMerIndex)
                                && !entry.getKey().contains(key)).count();
                        if (count > 0) {
                            continue;
                        }
                    }
                    // 创建或更新合并范围对象
                    CellRangeAddress cellAddresses = cellRangeAddressMap.get(key);
                    CellRangeAddress cellRangeAddress = new CellRangeAddress(row.getRowNum() - 1, row.getRowNum(),
                            needMerIndex, needMerIndex);
                    if (cellAddresses == null) {
                        cellRangeAddressMap.put(key, cellRangeAddress);
                    } else {
                        cellRangeAddress.setFirstRow(cellAddresses.getFirstRow());
                        cellRangeAddressMap.put(key, cellRangeAddress);
                    }
                    // 如果是最后一行,则将合并范围添加到sheet中
                    if (row.getRowNum() == totalDataRowCount) {
                        sheet.addMergedRegionUnsafe(cellRangeAddressMap.get(key));
                    }
                }
            } else {
                // 如果不需要合并,则移除相应的合并范围对象
                for (Integer needMerIndex : mergeValueColumnIndex) {
                    String key = String.format("%s-%s", k, needMerIndex);
                    CellRangeAddress cellAddresses = cellRangeAddressMap.get(key);
                    if (cellAddresses != null) {
                        sheet.addMergedRegionUnsafe(cellRangeAddressMap.get(key));
                        cellRangeAddressMap.remove(key);
                    }
                }
            }
        });
    }

    /**
     * 获取单元格的字符串内容
     *
     * @param cell 单元格对象
     * @return 单元格的字符串内容
     */
    private String getStringCellValue(Cell cell) {
        if (cell.getCellType() == CellType.STRING) {
            return cell.getStringCellValue();
        } else {
            return String.valueOf(cell.getNumericCellValue());
        }
    }

    /**
     * 初始化主键下标和需要合并字段的下标
     */
    private void lazyInit() {
        // 获取DTO所有的属性
        Field[] fields = this.elementType.getDeclaredFields();
        boolean pkInitialized = false;

        // 遍历所有的字段
        for (Field theField : fields) {
            // 获取@ExcelProperty注解
            ExcelProperty easyExcelAnno = theField.getAnnotation(ExcelProperty.class);
            // 为空,则表示该字段不需要导入到excel,直接处理下一个字段
            if (null == easyExcelAnno) {
                continue;
            }
            // 获取自定义的注解
            CustomMerge customMerge = theField.getAnnotation(CustomMerge.class);

            // 没有@CustomMerge注解的默认不合并
            if (null == customMerge) {
                continue;
            }
            String[] pks = customMerge.value();
            // 判断是否有主键标识
            if (customMerge.isPk()) {
                if (ObjectUtils.isEmpty(pks)) {
                    throw new IllegalStateException(String.format("字段[%s]使用@CustomMerge注解isPk为true但未指定合并值", theField.getName()));
                }
                for (String pk : pks) {
                    List pkColumnIndex = pkColumnIndexMap.get(pk);
                    if (pkColumnIndex == null) {
                        pkColumnIndex = new ArrayList<>();
                    }
                    pkColumnIndex.add(easyExcelAnno.index());
                    pkColumnIndexMap.put(pk, pkColumnIndex);
                    pkInitialized = true; // 标记主键已初始化
                }
                if (pks.length > 0) {
                    pkColumnIndexSet.add(easyExcelAnno.index());
                }
            }

            // 判断是否需要合并
            if (ObjectUtils.isNotEmpty(pks)) {
                for (String pk : pks) {
                    List needMergeColumnIndex = mergeValueColumnIndexMap.get(pk);
                    if (needMergeColumnIndex == null) {
                        needMergeColumnIndex = new ArrayList<>();
                    }
                    needMergeColumnIndex.add(easyExcelAnno.index());
                    mergeValueColumnIndexMap.put(pk, needMergeColumnIndex);
                }
            }
        }

        // 没有指定主键,则异常
        if (!pkInitialized) {
            throw new IllegalStateException("使用@CustomMerge注解必须指定主键");
        }
    }
}

3 使用方式

          WriteSheet sheet2 = EasyExcel.writerSheet("卡明细补助").registerWriteHandler(new CustomMergeStrategy(LdYcTrafficAllowanceExportDetailVo.class, detailVos.size(), new int[]{2, 12, 15}))
                    .head(LdYcTrafficAllowanceExportDetailVo.class)
                    .build();

4 实体类

package com.test.domain.vo;

import com.alibaba.excel.annotation.ExcelIgnore;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.write.style.ContentStyle;
import com.alibaba.excel.enums.poi.HorizontalAlignmentEnum;
import com.alibaba.excel.enums.poi.VerticalAlignmentEnum;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yc.utils.CustomMerge;
import com.yfld.common.core.annotation.Excel;
import lombok.Data;

import java.util.Date;

/**
 * 公共交通补助明细列表
 */
@Data
public class TrafficAllowanceExportDetailVo {
...
   
//
    /** 打卡日期 */
    @JsonFormat(pattern = "yyyy-MM-dd")
    @Excel(name = "打卡日期", width = 30, dateFormat = "yyyy-MM-dd")
    @ExcelProperty(value = "打卡日期", index = 15)
    @CustomMerge(value = {"serverRoomCode", "nickName", "checkInDate"}, isPk = true)
    @ContentStyle(horizontalAlignment = HorizontalAlignmentEnum.CENTER, verticalAlignment = VerticalAlignmentEnum.CENTER)
    private String checkInDate;
    /** 交通补助(元) */
    @Excel(name = "交通补助")
    @ExcelProperty(value = "交通补助", index = 16)
    @CustomMerge(value = {"serverRoomCode", "nickName", "checkInDate"}, isPk = true)
    @ContentStyle(horizontalAlignment = HorizontalAlignmentEnum.CENTER, verticalAlignment = VerticalAlignmentEnum.CENTER)
    private String transportAllowance;
}

第二种实现方式

通过定义注解+实现CellWriteHandler接口中的afterRowDispose根据指定的字段索引去做自定义key传入的数据需要做成map结构方便后续合并数据。

package com.test.utils.excel;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.yc.domain.vo.LdYcTrafficAllowanceExportDetailVo;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;

import java.util.*;

public class TrafficAllowanceCellWriteHandler implements CellWriteHandler {

    private final Map<String, List> data;

    private final Map groupRowMap; // 记录每个分组的起始行

    private final WriteCellStyle centerStyle; // 居中样式

    private final List groupKeyIndex;


    public TrafficAllowanceCellWriteHandler(Map<String, List> data, List groupKeyIndex) {
        this.data = data;
        this.groupRowMap = new HashMap<>();
        this.centerStyle = createCenterStyle();
        this.groupKeyIndex = groupKeyIndex;
    }

    /**
     * 创建居中样式
     */
    private WriteCellStyle createCenterStyle() {
        WriteCellStyle style = new WriteCellStyle();
        style.setHorizontalAlignment(HorizontalAlignment.CENTER); // 水平居中
        style.setVerticalAlignment(VerticalAlignment.CENTER); // 垂直居中
        return style;
    }

    @Override
    public void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder,
                                 List<WriteCellData> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
        if (isHead || cell.getRowIndex() == 0) {
            return;
        }

        Sheet sheet = writeSheetHolder.getSheet();
        int currentRowIndex = cell.getRow().getRowNum();
        String key = getRowKey(cell.getRow());

        // 遍历分组后的数据
//        for (Map.Entry<String, List> entry : data.entrySet()) {
////            String key = entry.getKey();
//             // 移动到下一个分组的起始行
//        }
        List orders = data.get(key);
        if (CollectionUtil.isNotEmpty(orders) && orders.size() > 1) {
            // 如果当前行是该分组的起始行
            if (!groupRowMap.containsKey(key)) {
                groupRowMap.put(key, currentRowIndex); // 记录分组的起始行
                if (orders.size() > 1) {
                    int lastRow = currentRowIndex + orders.size() - 1;
                    // 合并用户名和用户编码列
                    CellRangeAddress checkInDateRange = new CellRangeAddress(currentRowIndex, lastRow, 15, 15); // 用户名列
                    CellRangeAddress priceRange = new CellRangeAddress(currentRowIndex, lastRow, 16, 16); // 用户编码列
                    sheet.addMergedRegion(checkInDateRange);
                    sheet.addMergedRegion(priceRange);
                    // 设置合并区域的样式
                    setMergedRegionStyle(sheet, checkInDateRange, centerStyle);
                    setMergedRegionStyle(sheet, priceRange, centerStyle);
                }
//                currentRowIndex += orders.size();
            }

        }

    }

    /**
     * 设置合并区域的样式
     */
    private void setMergedRegionStyle(Sheet sheet, CellRangeAddress range, WriteCellStyle writeCellStyle) {
        Workbook workbook = sheet.getWorkbook();
        CellStyle cellStyle = workbook.createCellStyle();

        // 设置水平对齐方式
        if (writeCellStyle.getHorizontalAlignment() != null) {
            cellStyle.setAlignment(writeCellStyle.getHorizontalAlignment());
        }

        // 设置垂直对齐方式
        if (writeCellStyle.getVerticalAlignment() != null) {
            cellStyle.setVerticalAlignment(writeCellStyle.getVerticalAlignment());
        }

        // 设置字体
        if (writeCellStyle.getWriteFont() != null) {
            Font font = workbook.createFont();
            WriteFont writeFont = writeCellStyle.getWriteFont();
            if (writeFont.getFontName() != null) {
                font.setFontName(writeFont.getFontName());
            }
            if (writeFont.getFontHeightInPoints() != null) {
                font.setFontHeightInPoints(writeFont.getFontHeightInPoints());
            }
            if (writeFont.getBold() != null) {
                font.setBold(writeFont.getBold());
            }
            cellStyle.setFont(font);
        }

        // 设置背景颜色
        if (writeCellStyle.getFillForegroundColor() != null) {
            cellStyle.setFillForegroundColor(writeCellStyle.getFillForegroundColor());
            cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        }

        // 设置边框
        if (writeCellStyle.getBorderLeft() != null) {
            cellStyle.setBorderLeft(writeCellStyle.getBorderLeft());
        }
        if (writeCellStyle.getBorderRight() != null) {
            cellStyle.setBorderRight(writeCellStyle.getBorderRight());
        }
        if (writeCellStyle.getBorderTop() != null) {
            cellStyle.setBorderTop(writeCellStyle.getBorderTop());
        }
        if (writeCellStyle.getBorderBottom() != null) {
            cellStyle.setBorderBottom(writeCellStyle.getBorderBottom());
        }

        // 应用样式到合并区域的所有单元格
        for (int row = range.getFirstRow(); row <= range.getLastRow(); row++) {
            Row sheetRow = sheet.getRow(row);
            if (sheetRow == null) {
                sheetRow = sheet.createRow(row);
            }
            for (int col = range.getFirstColumn(); col <= range.getLastColumn(); col++) {
                Cell cell = sheetRow.getCell(col);
                if (cell == null) {
                    cell = sheetRow.createCell(col);
                }
                cell.setCellStyle(cellStyle);
            }
        }
    }

    private String getRowKey(Row row) {
        StringBuilder key = new StringBuilder();
        for (int i : groupKeyIndex) {
            Cell cell = row.getCell(i);
            if (cell != null) {
                key.append(cell.getStringCellValue());
            }
        }
        return key.toString();
//        Cell roomCodeCell = row.getCell(12);
//        if (roomCodeCell != null) {
//            key.append(roomCodeCell.getStringCellValue());
//        }
//        Cell nickNameCell = row.getCell(2);
//        if (nickNameCell != null)
//            key.append(nickNameCell.getStringCellValue());
//        Cell chenkInDateCell = row.getCell(15);
//        if (chenkInDateCell != null)
//            key.append(chenkInDateCell.getStringCellValue());
//        return key.toString();
    }
}

第二种实现方式使用方法

  // 创建并注册第二个Sheet(合并策略在此处处理)
            Map<String, List> detailMap = detailVos.stream().collect(Collectors.groupingBy(exportData -> exportData.getServerRoomCode() + exportData.getNickName() + exportData.getCheckInDate()));
  // 多个字段组合key标记excel中的位置index
            List groupKeyIndex = Arrays.asList(12, 2, 15);
            WriteSheet sheet2 = EasyExcel.writerSheet("项目打卡明细补助")
                    .head(LdYcTrafficAllowanceExportDetailVo.class)
                    .registerWriteHandler(new TrafficAllowanceCellWriteHandler(detailMap, groupKeyIndex))
                    .build();

第一种实现方式原文转载自这里在此基础上进行了调整,增加了多个字段组合key的实现方式通过参数产地

EasyExcel合并单元格,通过注解方式实现自定义合并策略,RowWriteHandler高效率实现-CSDN博客

相关推荐

JPA实体类注解,看这篇就全会了

基本注解@Entity标注于实体类声明语句之前,指出该Java类为实体类,将映射到指定的数据库表。name(可选):实体名称。缺省为实体类的非限定名称。该名称用于引用查询中的实体。不与@Tab...

Dify教程02 - Dify+Deepseek零代码赋能,普通人也能开发AI应用

开始今天的教程之前,先解决昨天遇到的一个问题,docker安装Dify的时候有个报错,进入Dify面板的时候会出现“InternalServerError”的提示,log日志报错:S3_USE_A...

用离散标记重塑人体姿态:VQ-VAE实现关键点组合关系编码

在人体姿态估计领域,传统方法通常将关键点作为基本处理单元,这些关键点在人体骨架结构上代表关节位置(如肘部、膝盖和头部)的空间坐标。现有模型对这些关键点的预测主要采用两种范式:直接通过坐标回归或间接通过...

B 客户端流RPC (clientstream Client Stream)

客户端编写一系列消息并将其发送到服务器,同样使用提供的流。一旦客户端写完消息,它就等待服务器读取消息并返回响应gRPC再次保证了单个RPC调用中的消息排序在客户端流RPC模式中,客户端会发送多个请...

我的模型我做主02——训练自己的大模型:简易入门指南

模型训练往往需要较高的配置,为了满足友友们的好奇心,这里我们不要内存,不要gpu,用最简单的方式,让大家感受一下什么是模型训练。基于你的硬件配置,我们可以设计一个完全在CPU上运行的简易模型训练方案。...

开源项目MessageNest打造个性化消息推送平台多种通知方式

今天介绍一个开源项目,MessageNest-可以打造个性化消息推送平台,整合邮件、钉钉、企业微信等多种通知方式。定制你的消息,让通知方式更灵活多样。开源地址:https://github.c...

使用投机规则API加快页面加载速度

当今的网络用户要求快速导航,从一个页面移动到另一个页面时应尽量减少延迟。投机规则应用程序接口(SpeculationRulesAPI)的出现改变了网络应用程序接口(WebAPI)领域的游戏规则。...

JSONP安全攻防技术

关于JSONPJSONP全称是JSONwithPadding,是基于JSON格式的为解决跨域请求资源而产生的解决方案。它的基本原理是利用HTML的元素标签,远程调用JSON文件来实现数据传递。如果...

大数据Doris(六):编译 Doris遇到的问题

编译Doris遇到的问题一、js_generator.cc:(.text+0xfc3c):undefinedreferenceto`well_known_types_js’查找Doris...

网页内嵌PDF获取的办法

最近女王大人为了通过某认证考试,交了2000RMB,官方居然没有给线下教材资料,直接给的是在线教材,教材是PDF的但是是内嵌在网页内,可惜却没有给具体的PDF地址,无法下载,看到女王大人一点点的截图保...

印度女孩被邻居家客人性骚扰,父亲上门警告,反被围殴致死

微信的规则进行了调整希望大家看完故事多点“在看”,喜欢的话也点个分享和赞这样事儿君的推送才能继续出现在你的订阅列表里才能继续跟大家分享每个开怀大笑或拍案惊奇的好故事啦~话说只要稍微关注新闻的人,应该...

下周重要财经数据日程一览 (1229-0103)

下周焦点全球制造业PMI美国消费者信心指数美国首申失业救济人数值得注意的是,下周一希腊还将举行第三轮总统选举需要谷歌日历同步及部分智能手机(安卓,iPhone)同步日历功能的朋友请点击此链接,数据公布...

PyTorch 深度学习实战(38):注意力机制全面解析

在上一篇文章中,我们探讨了分布式训练实战。本文将深入解析注意力机制的完整发展历程,从最初的Seq2Seq模型到革命性的Transformer架构。我们将使用PyTorch实现2个关键阶段的注意力机制变...

聊聊Spring AI的EmbeddingModel

序本文主要研究一下SpringAI的EmbeddingModelEmbeddingModelspring-ai-core/src/main/java/org/springframework/ai/e...

前端分享-少年了解过iframe么

iframe就像是HTML的「内嵌画布」,允许在页面中加载独立网页,如同在画布上叠加另一幅动态画卷。核心特性包括:独立上下文:每个iframe都拥有独立的DOM/CSS/JS环境(类似浏...