Java之利用openCsv將csv文件導入mysql數據庫


前兩天干活兒的時候有個需求,前台導入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; }

 

這里會將你前端發送過來的文件做讀取后直接入庫,不會生成中間文件,希望這篇文章能對你有幫助,有問題可以評論區交流哦。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM