前兩天干活兒的時候有個需求,前台導入csv文件,后台要做接收處理,mysql數據庫中,項目用的springboot+Vue+mybatisPlus實現,下面詳細記錄一下實現流程。
1.Controller層部分:
/** * 讀取csv文件,批量插入到數據庫中 */ @RequestMapping("/importcsv") @RequiresPermissions("xxx:xxxxx:xxx") public R importCsv(@RequestParam("file") MultipartFile file) throws IOException, CsvException { if (null == file) { return R.error("上傳文件為空"); } List<xxxEntity> csvFileContentList = xxxService.getCsvFileContent(file); boolean b = xxxService.saveBatch(csvFileContentList); if (b) { return R.ok("文件導入成功"); } else { return R.ok("文件導入失敗"); } }
這里是先將前端傳遞過來的file交給getCsvFileContent方法處理,生成要批量插入的list,然后再用mybatisPlus做批量插入。
2.實現類部分:
@Override public List<xxxEntity> getCsvFileContent(MultipartFile file) throws IOException, CsvException { //讀取csv文件 String charset = "GBK"; Reader reader = new InputStreamReader(file.getInputStream(), charset); CSVReader csvReader = new CSVReader(reader); csvReader.readNext(); List<String[]> csvList = csvReader.readAll(); List<xxxEntity> xxxList = new ArrayList<>(); xxxEntity xxx = null; for(String[] csv : csvList){ xxx = new xxxEntity(); if(null != csv && csv.length != 0){
//這里是查詢要入庫的數據是不是在數據庫中已存在 xxxEntity xxxx = findOneByxxxAndxxx(csv[0], csv[1]); if (xxxx == null) { xxx.setXxx(csv[0]); xxx.setXxx(csv[1]); xxx.setXxx(csv[2]); }else { continue; } } xxxList.add(xxx); } return xxxList; }
這里會將你前端發送過來的文件做讀取后直接入庫,不會生成中間文件,希望這篇文章能對你有幫助,有問題可以評論區交流哦。