gaoluyang
3 天以前 0f4aa5957957d9124e88da4490fac60da5324058
fix(excel): 兼容模板表头必填星号并完善部门/岗位导入校验

- 导入时自动去掉表头开头的 "*",避免带星号模板整列绑定失败导致字段全为 null
- 部门/岗位导入前校验名称、编码、排序、状态等必填项,空名称不再生成 null 的 Map key
- 修复导入失败时响应序列化异常(Null key for a Map)和数据库非空约束系统异常

Co-Authored-By: Claude Code <noreply@anthropic.com>
已修改3个文件
99 ■■■■■ 文件已修改
yudao-framework/yudao-spring-boot-starter-excel/src/main/java/cn/iocoder/yudao/framework/excel/core/util/ExcelUtils.java 48 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
yudao-module-system/src/main/java/cn/iocoder/yudao/module/system/service/dept/DeptServiceImpl.java 19 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
yudao-module-system/src/main/java/cn/iocoder/yudao/module/system/service/dept/PostServiceImpl.java 32 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
yudao-framework/yudao-spring-boot-starter-excel/src/main/java/cn/iocoder/yudao/framework/excel/core/util/ExcelUtils.java
@@ -5,9 +5,11 @@
import cn.idev.excel.annotation.ExcelProperty;
import cn.idev.excel.context.AnalysisContext;
import cn.idev.excel.converters.longconverter.LongStringConverter;
import cn.idev.excel.enums.CellDataTypeEnum;
import cn.idev.excel.enums.CellExtraTypeEnum;
import cn.idev.excel.event.AnalysisEventListener;
import cn.idev.excel.metadata.CellExtra;
import cn.idev.excel.metadata.data.ReadCellData;
import cn.iocoder.yudao.framework.common.util.http.HttpUtils;
import cn.iocoder.yudao.framework.excel.core.handler.ColumnWidthMatchStyleStrategy;
import cn.iocoder.yudao.framework.excel.core.handler.RequiredHeaderWriteHandler;
@@ -69,12 +71,51 @@
    }
    public static <T> List<T> read(MultipartFile file, Class<T> head) throws IOException {
        AnalysisEventListener<T> headerNormalizeListener = new AnalysisEventListener<>() {
            @Override
            public void invokeHead(Map<Integer, ReadCellData<?>> headMap, AnalysisContext context) {
                normalizeHeadCells(headMap);
            }
            @Override
            public void invoke(T data, AnalysisContext context) {
            }
            @Override
            public void doAfterAllAnalysed(AnalysisContext context) {
            }
        };
        // 参考 https://t.zsxq.com/zM77F 帖子,增加 try 处理,兼容 windows 场景
        try (InputStream inputStream = file.getInputStream()) {
            return FastExcelFactory.read(inputStream, head, null)
            return FastExcelFactory.read(inputStream, head, headerNormalizeListener)
                    .autoCloseStream(false) // 不要自动关闭,交给 Servlet 自己处理
                    .doReadAllSync();
        }
    }
    /**
     * 去掉表头前面的必填星号。
     *
     * <p>导出模板时,{@link RequiredHeaderWriteHandler} 会给必填列的表头加上 "*" 前缀(如 "*部门名称"),
     * 而导入时 {@link ExcelProperty} 是按精确表头匹配的(如 "部门名称")。如果不去掉星号,
     * 整列都会绑定不上,字段全是 null,导入会报"系统异常"。
     *
     * <p>该方法在 {@code buildHead} 之前修改表头单元格的值,因此既兼容带星号的模板,
     * 也兼容用户手工去掉星号的文件。
     */
    private static void normalizeHeadCells(Map<Integer, ReadCellData<?>> headMap) {
        if (headMap == null) {
            return;
        }
        headMap.values().forEach(cellData -> {
            if (cellData == null || cellData.getType() != CellDataTypeEnum.STRING) {
                return;
            }
            String value = cellData.getStringValue();
            if (value != null && value.startsWith("*")) {
                cellData.setStringValue(value.substring(1).trim());
            }
        });
    }
    /**
@@ -149,6 +190,11 @@
        }
        @Override
        public void invokeHead(Map<Integer, ReadCellData<?>> headMap, AnalysisContext context) {
            normalizeHeadCells(headMap);
        }
        @Override
        public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
            sheetHeaderMap.put(context.readSheetHolder().getSheetNo(), headMap);
        }
yudao-module-system/src/main/java/cn/iocoder/yudao/module/system/service/dept/DeptServiceImpl.java
@@ -264,7 +264,24 @@
        importDepts.sort(Comparator.comparingInt(dept -> StrUtil.isEmpty(dept.getParentPath()) ? 0 : dept.getParentPath().split("/").length));
        // 3. 遍历导入
        for (DeptImportExcelVO importDept : importDepts) {
        for (int i = 0; i < importDepts.size(); i++) {
            DeptImportExcelVO importDept = importDepts.get(i);
            // 3.0 校验必填项:名称为空会生成 null 的 Map key,导致响应序列化失败;
            // 顺序、状态为空会触发数据库非空约束,直接抛系统异常
            String rowLabel = StrUtil.blankToDefault(importDept.getName(), "第 " + (i + 1) + " 条记录");
            if (StrUtil.isBlank(importDept.getName())) {
                respVO.getFailureDeptNames().put(rowLabel, "部门名称不能为空,请补全 Excel 的「部门名称」列后重新导入");
                continue;
            }
            if (importDept.getSort() == null) {
                respVO.getFailureDeptNames().put(rowLabel, "显示顺序不能为空,请补全 Excel 的「显示顺序」列后重新导入");
                continue;
            }
            if (importDept.getStatus() == null) {
                respVO.getFailureDeptNames().put(rowLabel, "状态未填写或不是「开启/关闭」,请填写 Excel 的「状态」列后重新导入");
                continue;
            }
            // 3.1 获取父部门 ID
            Long parentId = DeptDO.PARENT_ID_ROOT;
            if (StrUtil.isNotEmpty(importDept.getParentPath())) {
yudao-module-system/src/main/java/cn/iocoder/yudao/module/system/service/dept/PostServiceImpl.java
@@ -1,6 +1,7 @@
package cn.iocoder.yudao.module.system.service.dept;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
@@ -174,7 +175,28 @@
        }
        PostImportRespVO respVO = PostImportRespVO.builder().createPostNames(new ArrayList<>())
                .updatePostNames(new ArrayList<>()).failurePostNames(new LinkedHashMap<>()).build();
        importPosts.forEach(importPost -> {
        for (int i = 0; i < importPosts.size(); i++) {
            PostImportExcelVO importPost = importPosts.get(i);
            // 校验必填项:名称为空会生成 null 的 Map key,导致响应序列化失败;
            // 编码、排序、状态为空会触发数据库非空约束,直接抛系统异常
            String rowLabel = StrUtil.blankToDefault(importPost.getName(), "第 " + (i + 1) + " 条记录");
            if (StrUtil.isBlank(importPost.getName())) {
                respVO.getFailurePostNames().put(rowLabel, "岗位名称不能为空,请补全 Excel 的「岗位名称」列后重新导入");
                continue;
            }
            if (StrUtil.isBlank(importPost.getCode())) {
                respVO.getFailurePostNames().put(rowLabel, "岗位编码不能为空,请补全 Excel 的「岗位编码」列后重新导入");
                continue;
            }
            if (importPost.getSort() == null) {
                respVO.getFailurePostNames().put(rowLabel, "岗位排序不能为空,请补全 Excel 的「岗位排序」列后重新导入");
                continue;
            }
            if (importPost.getStatus() == null) {
                respVO.getFailurePostNames().put(rowLabel, "状态未填写或不是「开启/关闭」,请填写 Excel 的「状态」列后重新导入");
                continue;
            }
            // 校验,判断是否有不符合的原因
            try {
                validatePostForCreateOrUpdate(null, importPost.getName(), importPost.getCode());
@@ -184,7 +206,7 @@
                    // ignore
                } else {
                    respVO.getFailurePostNames().put(importPost.getName(), ex.getMessage());
                    return;
                    continue;
                }
            }
@@ -197,13 +219,13 @@
                PostDO post = BeanUtils.toBean(importPost, PostDO.class);
                postMapper.insert(post);
                respVO.getCreatePostNames().add(importPost.getName());
                return;
                continue;
            }
            // 如果存在,判断是否允许更新
            if (!isUpdateSupport) {
                respVO.getFailurePostNames().put(importPost.getName(), "岗位名或编码已经存在");
                return;
                continue;
            }
            // 更新岗位
@@ -211,7 +233,7 @@
            updatePost.setId(existPost.getId());
            postMapper.updateById(updatePost);
            respVO.getUpdatePostNames().add(importPost.getName());
        });
        }
        // 记录导入结果汇总,供 @LogRecord 的 success 文案引用
        OperateLogUtils.putImportSummary(respVO.getCreatePostNames(), respVO.getUpdatePostNames(),
                respVO.getFailurePostNames());