Java中excel字典转换

发布于:2025-07-18 ⋅ 阅读:(11) ⋅ 点赞:(0)

✅ 背景说明

EasyExcel 原生的 @ExcelProperty 注解不支持 dictType(不像那样有 @Excel(dictType="xxx")),所以如果你想实现字典翻译功能,就需要自己实现 Converter 接口,比如 DictConvert


✅ 什么是 DictConvert

DictConvert 是你可以 自定义的通用字段转换器类,其核心思想是:

  • 输入参数:字典类型 dictType(比如 "sys_user_status"

  • 行为

    • Java 值 "1" → Excel 中显示 "启用"

    • Excel 显示 "启用" → Java 中变成 "1"


✅ 接口定义

下面是一个典型的 DictConvert 实现

是一个 Excel 导入导出过程中的 数据字典转换器 DictConvert,它是配合 EasyExcel 使用的,用于将 Excel 中的“中文字段”与系统中的“字典值”进行自动双向转换

方向 行为 说明
Excel → Java 中文值 ⇒ 字典编码 如 “启用” → "1"
Java → Excel 字典编码 ⇒ 中文值 如 "1" → “启用”

 并且通过自定义注解 @DictFormat("dictType") 标注字段,让你不需要为每个字段写单独的 Converter



/**
 * Excel 数据字典转换器
 *
 * @author 芋道源码
 */
@Slf4j
public class DictConvert implements Converter<Object> {

    @Override
    public Class<?> supportJavaTypeKey() {
        throw new UnsupportedOperationException("暂不支持,也不需要");
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        throw new UnsupportedOperationException("暂不支持,也不需要");
    }

    @Override
    public Object convertToJavaData(ReadCellData readCellData, ExcelContentProperty contentProperty,
                                    GlobalConfiguration globalConfiguration) {
        // 使用字典解析
        String type = getType(contentProperty);
        String label = readCellData.getStringValue();
        String value = DictFrameworkUtils.parseDictDataValue(type, label);
        if (value == null) {
            log.error("[convertToJavaData][type({}) 解析不掉 label({})]", type, label);
            return null;
        }
        // 将 String 的 value 转换成对应的属性
        Class<?> fieldClazz = contentProperty.getField().getType();
        return Convert.convert(fieldClazz, value);
    }

    @Override
    public WriteCellData<String> convertToExcelData(Object object, ExcelContentProperty contentProperty,
                                                    GlobalConfiguration globalConfiguration) {
        // 空时,返回空
        if (object == null) {
            return new WriteCellData<>("");
        }

        // 使用字典格式化
        String type = getType(contentProperty);
        String value = String.valueOf(object);
        String label = DictFrameworkUtils.parseDictDataLabel(type, value);
        if (label == null) {
            log.error("[convertToExcelData][type({}) 转换不了 label({})]", type, value);
            return new WriteCellData<>("");
        }
        // 生成 Excel 小表格
        return new WriteCellData<>(label);
    }

    private static String getType(ExcelContentProperty contentProperty) {
        return contentProperty.getField().getAnnotation(DictFormat.class).value();
    }

}

 


✅ 使用方法

你在导出类中这样使用:


@ExcelProperty(value = "状态", converter = UserStatusDictConvert.class) private String status;

或者想进一步封装成通用的用法(多个字段共享)可借助策略或注册器统一配置。


✅ 总结一下

项目 说明
名称 DictConvert 是自定义的 EasyExcel 通用字段转换器
作用 实现字典值与显示名称之间的双向转换
用途 用于 Excel 的导入导出字段字典翻译
优点 多字段通用、支持动态加载字典(如从 Redis、数据库)


网站公告

今日签到

点亮在社区的每一天
去签到