luodangjia
2025-01-01 2dc478231fd09a88a4d86d44388ae807aca08bc5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package com.sinata.system.conveter;
 
import cn.idev.excel.converters.Converter;
import cn.idev.excel.enums.CellDataTypeEnum;
import cn.idev.excel.metadata.GlobalConfiguration;
import cn.idev.excel.metadata.data.WriteCellData;
import cn.idev.excel.metadata.property.ExcelContentProperty;
import com.sinata.system.annotation.FastExcel;
 
import java.lang.reflect.Field;
import java.lang.reflect.Method;
 
/**
 * 通用枚举转换器
 */
public class EConverter implements Converter<Integer> {
    @Override
    public Class supportJavaTypeKey() {
        //指定转换器接收参数类型
        return Integer.class;
    }
 
    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        //指定返回的参数类型
        return CellDataTypeEnum.STRING;
    }
 
    @Override
    public WriteCellData<?> convertToExcelData(Integer value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        //value:状态码  contentProperty:字段属性  globalConfiguration:全局配置
        //获取字段属性中的注解
        Field field = contentProperty.getField();
        //获取该字段所属枚举
        FastExcel fastExcel = field.getAnnotation(FastExcel.class);
        //获取注解中的枚举信息
        Class<? extends Enum> type = fastExcel.type();
        //获取枚举类的方法名 “getEnumByCode”就是自己编写的函数,Integer.class 指定入参类型
        Method codeOf = type.getMethod("getEnumByCode", Integer.class);
        //反射执行方法,此方法得到的是一个枚举实例(具体得到什么,结合自身项目)
        Object invoke = codeOf.invoke(type, value);
        //枚举实例调用getname方法,得到name的值
        Method getDesc = invoke.getClass().getMethod("getDesc");
        String name = String.valueOf(getDesc.invoke(invoke));
        //将转换的值进行返回
        return new WriteCellData(name);
    }
}