Jay
2024-11-01 03e8aca3ad6201c0d74e00d4c8d7367cdaaa54f9
提交 | 用户 | 时间
e7c126 1 package com.iailab.framework.excel.core.convert;
H 2
3 import cn.hutool.core.convert.Convert;
4 import com.iailab.framework.dict.core.DictFrameworkUtils;
5 import com.iailab.framework.excel.core.annotations.DictFormat;
6 import com.alibaba.excel.converters.Converter;
7 import com.alibaba.excel.enums.CellDataTypeEnum;
8 import com.alibaba.excel.metadata.GlobalConfiguration;
9 import com.alibaba.excel.metadata.data.ReadCellData;
10 import com.alibaba.excel.metadata.data.WriteCellData;
11 import com.alibaba.excel.metadata.property.ExcelContentProperty;
12 import lombok.extern.slf4j.Slf4j;
13
14 /**
15  * Excel 数据字典转换器
16  *
17  * @author iailab
18  */
19 @Slf4j
20 public class DictConvert implements Converter<Object> {
21
22     @Override
23     public Class<?> supportJavaTypeKey() {
24         throw new UnsupportedOperationException("暂不支持,也不需要");
25     }
26
27     @Override
28     public CellDataTypeEnum supportExcelTypeKey() {
29         throw new UnsupportedOperationException("暂不支持,也不需要");
30     }
31
32     @Override
33     public Object convertToJavaData(ReadCellData readCellData, ExcelContentProperty contentProperty,
34                                     GlobalConfiguration globalConfiguration) {
35         // 使用字典解析
36         String type = getType(contentProperty);
37         String label = readCellData.getStringValue();
38         String value = DictFrameworkUtils.parseDictDataValue(type, label);
39         if (value == null) {
40             log.error("[convertToJavaData][type({}) 解析不掉 label({})]", type, label);
41             return null;
42         }
43         // 将 String 的 value 转换成对应的属性
44         Class<?> fieldClazz = contentProperty.getField().getType();
45         return Convert.convert(fieldClazz, value);
46     }
47
48     @Override
49     public WriteCellData<String> convertToExcelData(Object object, ExcelContentProperty contentProperty,
50                                                     GlobalConfiguration globalConfiguration) {
51         // 空时,返回空
52         if (object == null) {
53             return new WriteCellData<>("");
54         }
55
56         // 使用字典格式化
57         String type = getType(contentProperty);
58         String value = String.valueOf(object);
59         String label = DictFrameworkUtils.getDictDataLabel(type, value);
60         if (label == null) {
61             log.error("[convertToExcelData][type({}) 转换不了 label({})]", type, value);
62             return new WriteCellData<>("");
63         }
64         // 生成 Excel 小表格
65         return new WriteCellData<>(label);
66     }
67
68     private static String getType(ExcelContentProperty contentProperty) {
69         return contentProperty.getField().getAnnotation(DictFormat.class).value();
70     }
71
72 }