public static List<Object> readCsvIntoVO(String readPath, Class<?> clazz) {
List<Object> result = new ArrayList<>();
Field[] fields = clazz.getDeclaredFields();
try {
// 以#分割
CsvReader csvReader = new CsvReader(readPath,',', Charset.forName("UTF-8"));
csvReader.readHeaders(); // 跳过表头 如果需要表头的话,不要写这句。
String[] head = csvReader.getHeaders(); //获取表头
while (csvReader.readRecord())
{
Object record = clazz.newInstance();
Map<String, String> map = new HashMap<String, String>();
for (String s : head) {
String name = s.trim();
if (name.charAt(0) == '\uFEFF') {
name = name.substring(1);
}
map.put(name,csvReader.get(s));
System.out.println(s + ":" + csvReader.get(s));
// String name = s.trim();
// for (Field field : fields) {
// field.setAccessible(true);
//
// if (name.equals(field.getName())) {
// Method method = clazz.getMethod("set" + name.substring(0, 1).toUpperCase() + name.substring(1), field.getType());
// method.invoke(record, StringUtils.get(field.getType(),csvReader.get(s)));
// break;
// }
// }
// Field f = record.getClass().getDeclaredField(s);
// f.setAccessible(true);
// f.set(record, csvReader.get(s));
}
BeanUtils.populate(record, map);
result.add(record);
}
csvReader.close();
} catch (FileNotFoundException e) {
throw new RuntimeException("文件未找到");
} catch (IOException e) {
throw new RuntimeException(e.getMessage());
} catch (IllegalAccessException | InstantiationException | InvocationTargetException e) {
e.printStackTrace();
}
return result;
}