package cn.lihu.jh.framework.excel.core.convert; import cn.hutool.core.convert.Convert; import cn.lihu.jh.framework.dict.core.DictFrameworkUtils; import cn.lihu.jh.framework.excel.core.annotations.DictFormat; import com.alibaba.excel.converters.Converter; import com.alibaba.excel.enums.CellDataTypeEnum; import com.alibaba.excel.metadata.GlobalConfiguration; import com.alibaba.excel.metadata.data.ReadCellData; import com.alibaba.excel.metadata.data.WriteCellData; import com.alibaba.excel.metadata.property.ExcelContentProperty; import lombok.extern.slf4j.Slf4j; /** * Excel 数据字典转换器 * * @author 芋道源码 */ @Slf4j public class DictConvert implements Converter { @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) { // 【本需求】与导出方向一致:字典缺项属数据问题,用 WARN 而不是 ERROR(避免导入时刷红日志) log.warn("[convertToJavaData][type({}) 未找到字典项 label({}),按 null 处理]", type, label); return null; } // 将 String 的 value 转换成对应的属性 Class fieldClazz = contentProperty.getField().getType(); return Convert.convert(fieldClazz, value); } @Override public WriteCellData 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.getDictDataLabel(type, value); if (label == null) { // 【本需求】字典里没有这个值时,属于"数据没配字典",不是系统错误: // 原来用 log.error,导出 N 行就会刷 N 条 ERROR(例如"患者性别=0"在字典里没有 0), // 现场看着像系统出故障。这里降为 WARN,仍保留可追溯信息。 // 返回值保持空单元格(比直接输出原始值 "0" 更合理)。 log.warn("[convertToExcelData][type({}) 未找到字典项 value({}),导出为空]", type, value); return new WriteCellData<>(""); } // 生成 Excel 小表格 return new WriteCellData<>(label); } private static String getType(ExcelContentProperty contentProperty) { return contentProperty.getField().getAnnotation(DictFormat.class).value(); } }