// 重要包出处
import com.csvreader.CsvReader;
import com.google.common.collect.Lists;
import jodd.util.CsvUtil;
import org.apache.commons.io.input.BOMInputStream;
import org.apache.commons.beanutils.PropertyUtils;
/**
* 读取Csv文件
*
* @param im 输入流
* @param clazz 映射的实体类
* @param columnMap csv表头对应的字段名称
* @param <T>
* @return
* @throws Exception
*/
public static <T> List<T> readCsvToList(InputStream im, Class<T> clazz, Map<String, String> columnMap)
throws Exception {
List<String[]> csvFileList = new ArrayList<>();
CsvReader reader = new CsvReader(new InputStreamReader(new BOMInputStream(im)));
// 读取表头,跳过表头 如果需要表头的话,这句可以忽略
reader.readHeaders();
String[] headArray = reader.getHeaders();
// 逐行读入除表头的数据
int i = 0;
while (reader.readRecord()) {
String rawRecord = reader.getRawRecord();
String[] record = CsvUtil.toStringArray(rawRecord);
csvFileList.add(record);
log.info("读取" + i + "行");
i++;
}
reader.close();
if (ListUtils.listIsNull(csvFileList)) {
log.info("csv文件为空");
return null;
}
int size = csvFileList.size();
List<T> resultList = Lists.newArrayList();
for (int i1 = 0; i1 < size; i1++) {
String[] datas = csvFileList.get(i1);
T t = clazz.newInstance();
Set<Map.Entry<String, String>> entries = columnMap.entrySet();
for (Map.Entry<String, String> entry : entries) {
String key = entry.getKey();
int idx = ArrayUtils.findIndex(headArray, key);
if (idx == -1) {
continue;
}
String data = datas[idx];
String field = entry.getValue();
PropertyUtils.setProperty(t, field, data);
}
resultList.add(t);
}
return resultList;
}
public static <T> int findIndex(T[] array, T t) throws UnsupportedEncodingException {
int idx = -1;
if (Objects.isNull(t)) {
return idx;
}
for (int i = 0; i < array.length; i++) {
if (Objects.nonNull(array[i]) && Objects.equals(t, array[i])) {
idx = i;
break;
}
}
return idx;
}
调用
@Test
public void test02() throws Exception {
FileInputStream fileInputStream = new FileInputStream(new File("C:\\Users\\Desktop\\locations.csv"));
Map<String, String> excelMap = new HashMap<>();
excelMap.put("经度", "lon");
excelMap.put("纬度", "lat");
excelMap.put("城市", "city");
excelMap.put("地址", "address");
List<ImportLocationsModel> importLocationsModels =
readCsvToList(fileInputStream, ImportLocationsModel.class, excelMap);
System.out.println(JSONObject.toJSONString(importLocationsModels));
}