5
建议描述 目前码表转换性别转换、状态转换等貌似都要单独新建一个Converter,如果Converter提供一个参数设置的方法(注入json格式的数据,可初始化多个可变参数),导入导出带码表的数据就使用这个公共转换器方便很多,不清楚是否可行。 实现类似如下
public interface Converter<T> {
// 新增方法begin
void setConverterParams(String converterParams);
// 新增方法end
Class supportJavaTypeKey();
CellDataTypeEnum supportExcelTypeKey();
T convertToJavaData(CellData cellData, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) throws Exception;
CellData convertToExcelData(T value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration)
throws Exception;
}
public @interface ExcelProperty {
String[] value() default {""};
int index() default -1;
Class<? extends Converter> converter() default AutoConverter.class;
String converterParams() default "";
@Deprecated
String format() default "";
}
@ExcelProperty(value = "性别", converter = DictConverter.class, converterParams = "{\"dictType\":\"userSex\"}")
private String sex;
public class DictConverter implements Converter<String> {
private String dictType;
@Override
public void setConverterParams(String converterParams) {
if (converterParams == null || converterParams.length() == 0) {
return;
}
Map<String, Object> paramsMap = JacksonUtil.strToObj(converterParams, HashMap.class);
if (paramsMap == null) {
return;
}
this.dictType = (String) paramsMap.get("dictType");
}
@Override
public Class<String> supportJavaTypeKey() {
return String.class;
}
@Override
public CellDataTypeEnum supportExcelTypeKey() {
return CellDataTypeEnum.STRING;
}
@Override
public String convertToJavaData(CellData cellData, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) {
if (this.dictType == null || this.dictType.length() == 0) {
throw new SysException("DictType can not be null");
}
String value = CacheUtil.getDictValue(this.dictType, cellData.getStringValue());
if (value == null || value.length() == 0) {
value = cellData.getStringValue();
}
return value;
}
@Override
public CellData convertToExcelData(String value, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) {
if (this.dictType == null || this.dictType.length() == 0) {
throw new SysException("DictType can not be null");
}
String desc = CacheUtil.getDictDesc(this.dictType, value);
if (desc == null || desc.length() == 0) {
desc = value;
}
return new CellData(desc);
}
}
ExcelHeadProperty类部分代码处理:
if (excelProperty != null) {
Class<? extends Converter> convertClazz = excelProperty.converter();
if (convertClazz != AutoConverter.class) {
try {
Converter converter = convertClazz.newInstance();
String converterParams = excelProperty.converterParams();
converter.setConverterParams(converterParams);
excelContentProperty.setConverter(converter);
} catch (Exception e) {
throw new ExcelCommonException("Can not instance custom converter:" + convertClazz.getName());
}
}
}