csv文件转java类

1.引入jar

compile group: 'org.apache.poi', name: 'poi', version: '4.0.1'
compile group: 'org.apache.poi', name: 'poi-ooxml', version: '4.0.1'

2.假设csv的格式如下所示

csv文件转java类_第1张图片

3.转换代码如下所示

public List getCsvData(){
    Map mapping = new
        HashMap();
    mapping.put("s_city_id", "s_city_id");
    mapping.put("s_city", "s_city");
    mapping.put("s_lat", "s_lat");
    mapping.put("s_lon", "s_lon");
    mapping.put("s_pop", "s_pop");
    mapping.put("s_country", "s_country");
    mapping.put("s_Volume", "s_Volume");
    mapping.put("e_city_id", "e_city_id");
    mapping.put("e_City", "e_City");
    mapping.put("e_lat", "e_lat");
    mapping.put("e_lon", "e_lon");
    mapping.put("e_pop", "e_pop");
    mapping.put("e_country", "e_country");
    mapping.put("e_vol", "e_vol");
    HeaderColumnNameTranslateMappingStrategy strategy =
        new HeaderColumnNameTranslateMappingStrategy();
    strategy.setType(CsvData.class);
    strategy.setColumnMapping(mapping);
    CSVReader csvReader = null;
    ClassLoader classLoader = getClass().getClassLoader();
    try {
        csvReader = new CSVReader(new FileReader
            (classLoader.getResource("1.csv").getFile()));
    }
    catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    CsvToBean csvToBean = new CsvToBean();
    List list = csvToBean.parse(strategy, csvReader);
   return list;
}

4.CsvData是对应的java bean,属性如下所示

csv文件转java类_第2张图片

你可能感兴趣的:(基础知识,springboot)