疯狂老司机 2020-01-09
前两天干活儿的时候有个需求,前台导入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;
}这里会将你前端发送过来的文件做读取后直接入库,不会生成中间文件,希望这篇文章能对你有帮助,有问题可以评论区交流哦。