fix: 修复 CellMergeStrategy 中 @ExcelIgnore 导致列合并错位的问题,以及修复合并字段未加@ExcelProperty注解导致空指针异常

This commit is contained in:
chengliejian 2025-08-07 15:44:18 +08:00
parent 5d69832423
commit 24d2ca0fff

View File

@ -3,6 +3,7 @@ package org.dromara.common.excel.core;
import cn.hutool.core.collection.CollUtil; import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ReflectUtil; import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.StrUtil;
import cn.idev.excel.annotation.ExcelIgnore;
import cn.idev.excel.annotation.ExcelProperty; import cn.idev.excel.annotation.ExcelProperty;
import cn.idev.excel.metadata.Head; import cn.idev.excel.metadata.Head;
import cn.idev.excel.write.handler.WorkbookWriteHandler; import cn.idev.excel.write.handler.WorkbookWriteHandler;
@ -75,25 +76,38 @@ public class CellMergeStrategy extends AbstractMergeStrategy implements Workbook
// 有注解的字段 // 有注解的字段
List<Field> mergeFields = new ArrayList<>(); List<Field> mergeFields = new ArrayList<>();
List<Integer> mergeFieldsIndex = new ArrayList<>(); List<Integer> mergeFieldsIndex = new ArrayList<>();
for (int i = 0; i < fields.length; i++) { // 实际 Excel 列索引忽略被 @ExcelIgnore 的字段
Field field = fields[i]; int excelColIndex = 0;
for (Field field : fields) {
if (field.isAnnotationPresent(ExcelIgnore.class)) {
// 忽略不导出的字段
continue;
}
if (field.isAnnotationPresent(CellMerge.class)) { if (field.isAnnotationPresent(CellMerge.class)) {
CellMerge cm = field.getAnnotation(CellMerge.class); CellMerge cm = field.getAnnotation(CellMerge.class);
mergeFields.add(field); mergeFields.add(field);
mergeFieldsIndex.add(cm.index() == -1 ? i : cm.index()); // CellMerge.index() 被设置了使用它否则用当前实际 Excel 列索引
mergeFieldsIndex.add(cm.index() == -1 ? excelColIndex : cm.index());
if (hasTitle) { if (hasTitle) {
ExcelProperty property = field.getAnnotation(ExcelProperty.class); ExcelProperty property = field.getAnnotation(ExcelProperty.class);
rowIndex = Math.max(rowIndex, property.value().length); if (property != null && property.value().length > 0) {
rowIndex = Math.max(rowIndex, property.value().length);
}
} }
} }
// 每处理一个未忽略的字段实际 Excel 列索引 +1
excelColIndex++;
} }
Map<Field, RepeatCell> map = new HashMap<>(); Map<Field, RepeatCell> map = new HashMap<>();
// 生成两两合并单元格 // 生成两两合并单元格
for (int i = 0; i < list.size(); i++) { for (int i = 0; i < list.size(); i++) {
Object rowObj = list.get(i);
for (int j = 0; j < mergeFields.size(); j++) { for (int j = 0; j < mergeFields.size(); j++) {
Field field = mergeFields.get(j); Field field = mergeFields.get(j);
Object val = ReflectUtils.invokeGetter(list.get(i), field.getName()); Object val = ReflectUtils.invokeGetter(rowObj, field.getName());
int colNum = mergeFieldsIndex.get(j); int colNum = mergeFieldsIndex.get(j);
if (!map.containsKey(field)) { if (!map.containsKey(field)) {