import java.lang.annotation.*;
/**
* 指定枚举类注解
*/
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface EasyExcel {
/**
* 控件类型
* @return
*/
Class<? extends Enum> type();
}
import lombok.Getter;
import java.util.HashMap;
import java.util.Map;
/**
* @Description:
* @DateTime: 2023/8/24 14:46
*/
@Getter
public enum MessageStatusEnum {
SET_UP(0, "UNREAD"),
RUNNING(1, "READ"),
;
public static Map<Integer, MessageStatusEnum> MAPS = new HashMap<>();
static {
for (MessageStatusEnum e : values()) {
MAPS.put(e.getCode(), e);
}
}
private final Integer code;
private final String name;
MessageStatusEnum(Integer code, String name) {
this.code = code;
this.name = name;
}
public static MessageStatusEnum codeOf(Object code) {
return MAPS.getOrDefault((Integer)code, null);
}
}
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.ruijie.common.core.annotation.EasyExcel;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
/**
* @Description: excel导出数值转字符串
* @DateTime: 2023/8/24 14:13
*/
public class CaseStateConverter implements Converter<Object> {
@Override
public Class supportJavaTypeKey() {
//指定状态码类型
return Object.class;
}
@Override
public CellDataTypeEnum supportExcelTypeKey() {
//指定需要获取的参数类型
return CellDataTypeEnum.STRING;
}
@Override
public WriteCellData<?> convertToExcelData(Object value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
//value:状态码 contentProperty:字段属性 globalConfiguration:全局配置
//获取字段属性中的注解
Field field = contentProperty.getField();
EasyExcel easyExcel = field.getAnnotation(EasyExcel.class);
//获取注解中的枚举信息
Class<? extends Enum> type = easyExcel.type();
//获取枚举类的方法名 “codeOf”就是自己编写的函数,Integer.class 指定入参类型
Method codeOf = type.getMethod("codeOf", Object.class);
//反射执行方法,此方法得到的是一个枚举实例(具体得到什么,结合自身项目)
Object invoke = codeOf.invoke(type, value);
//枚举实例调用getName方法,得到name的值
Method getName = invoke.getClass().getMethod("getName");
String name = String.valueOf(getName.invoke(invoke));
//将转换的值进行返回
return new WriteCellData<>(name);
}
}
实体类使用
/**
* 消息状态 0未读/1已读
*/
@ApiModelProperty(value = "消息状态 0未读/1已读")
@ExcelProperty(value = "messageStatus",converter = CaseStateConverter.class)
@EasyExcel(type = MessageStatusEnum.class)
private int messageStatus;