
com.github.houbb.iexcel.hutool.support.read.DefaultMapToBeanReader Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of iexcel-hutool Show documentation
Show all versions of iexcel-hutool Show documentation
Excel read and write tool based on hutool-poi.
package com.github.houbb.iexcel.hutool.support.read;
import cn.hutool.core.collection.CollectionUtil;
import com.github.houbb.heaven.util.lang.reflect.ClassUtil;
import com.github.houbb.heaven.util.util.MapUtil;
import com.github.houbb.iexcel.hutool.annotation.ExcelField;
import com.github.houbb.iexcel.hutool.exception.ExcelException;
import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;
/**
* 默认实现
* @param 泛型
*/
public class DefaultMapToBeanReader implements MapToBeanReader {
@Override
public T readToBean(Class tClass, Map map) {
try {
T instance = ClassUtil.newInstance(tClass);
if(MapUtil.isEmpty(map)) {
return instance;
}
// 考虑使用 cache
List fields = ClassUtil.getAllFieldList(tClass);
if(CollectionUtil.isEmpty(fields)) {
return instance;
}
for(Field field : fields) {
Object object = getFieldReadValue(field, map);
if(object == null) {
continue;
}
field.setAccessible(true);
//TODO: 后续使用 convert 优化
String text = object.toString();
field.set(instance, text);
}
return instance;
} catch (Exception e) {
throw new ExcelException(e);
}
}
/**
* 获取对应的读取自
* @param field 字段
* @param map map
* @return 结果
*/
private static Object getFieldReadValue(Field field, Map map) {
ExcelField excelField = field.getAnnotation(ExcelField.class);
if(excelField == null) {
return null;
}
if(!excelField.readRequire()) {
return null;
}
String headerName = excelField.headerName();
return map.get(headerName);
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy