? 背景說明
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> {@Overridepublic Class<?> supportJavaTypeKey() {throw new UnsupportedOperationException("暫不支持,也不需要");}@Overridepublic CellDataTypeEnum supportExcelTypeKey() {throw new UnsupportedOperationException("暫不支持,也不需要");}@Overridepublic 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);}@Overridepublic 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、數據庫) |