一,导入CSV的包
import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVRecord;
二, 代码如下
public ResponseEntity<Void> insertAreaInformation(@RequestParam String csvPath) throws IOException { String charset = "GBK"; FileInputStream fileInputStream = new FileInputStream(csvPath); Reader reader = new InputStreamReader(fileInputStream, charset); Iterable<CSVRecord> records = CSVFormat.EXCEL.parse(reader); Map<String, AreaInformation> resourceMap = new HashMap<>(); for (CSVRecord record : records) { if (record.getRecordNumber() == 1) { continue; } AreaInformation areaInformation = new AreaInformation(); areaInformation.setId(record.get(0)); areaInformation.setPid(record.get(1)); areaInformation.setLevel(record.get(2)); resourceMap.put(areaInformation.getId(), areaInformation); } if (resourceMap.size() > 0) { Lists.partition(new ArrayList<>(resourceMap.values()), 5000).stream().forEach(areaInformations -> areaInformationRepository.saveAll(areaInformations)); } return ResponseEntity.ok().build(); }