项目场景:
excel数据表导入
问题描述
excel导入我是采用hutool解析,解析后的数据格式为List<List<Object>>,在List<Object>转化为具体实体的过程中报错wrong number of arguments:
hutool解析代码块
ExcelReader reader = ExcelUtil.getReader(file.getInputStream()); List<List<Object>> rows = reader.read(2); for (List<Object> row : rows) { Object[] objects = row.toArray(); BaseRiskCarInfoDTOClass baseRiskCarInfoDTOClass =objectToBean(objects,BaseRiskCarInfoDTOClass.class); }
List<Object>转化为具体实体
/**
* 把List<Object[]>转换成List<T>
*/
public static <T> List<T> objectToBean(List<Object[]> objList, Class<T> clz) throws Exception{
if (objList==null || objList.size()==0) {
return null;
}
Class<?>[] cz = null;
Constructor<?>[] cons = clz.getConstructors();
for (Constructor<?> ct : cons) {
Class<?>[] clazz = ct.getParameterTypes();
if (objList.get(0).length == clazz.length) {
cz = clazz;
break;
}
}
List<T> list = new ArrayList<T>();
for (Object[] obj : objList) {
Constructor<T> cr = clz.getConstructor(cz);
list.add(cr.newInstance(obj));
}
return list;
}
原因分析:
objectToBean始终报错wrong number of arguments,具体可能是参数的数字类型有问题
解决方案:
改变实现方式,用一下方式List<Object>转化为具体实体(注意:list中的对象与实体一一对应,注意excel中对象个数需与list长度一致)
for (List<Object> row : rows) { Map<String,Object> rowMap = new HashMap<>(37); //注意:excel行数据与实体属性一一对应 Object[] objects = row.toArray(); Field[] fields = BaseRiskCarInfoDTOClass.class.getDeclaredFields(); for (int i = 0; i < objects.length; i++) { rowMap.put(fields[i].getName(),objects[i]); } BaseRiskCarInfoDTO baseRiskCarInfoDTO = BeanUtil.toBean(rowMap, BaseRiskCarInfoDTOClass.class); }