Springboot 上傳CSV文件並將數據存入數據庫


.xml文件依賴配置

  <!--csv依賴        -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-csv</artifactId>
            <version>1.7</version>
        </dependency>
          <!--上傳工具依賴        -->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
        </dependency>

java-CSV工具類

@Data
public class CsvImportUtil {
  

    //上傳文件的路徑
    private final static URL PATH = Thread.currentThread().getContextClassLoader().getResource("");




    /**
     * @return File  一般文件類型
     * @Description 上傳文件的文件類型
     * @Param multipartFile
     **/
    public static File uploadFile(MultipartFile multipartFile) {
        // 獲 取上傳 路徑
        String path = PATH.getPath() + multipartFile.getOriginalFilename();
        try {
            // 通過將給定的路徑名字符串轉換為抽象路徑名來創建新的 File實例
            File file = new File(path);
            // 此抽象路徑名表示的文件或目錄是否存在
            if (!file.getParentFile().exists()) {
                // 創建由此抽象路徑名命名的目錄,包括任何必需但不存在的父目錄
                file.getParentFile().mkdirs();
            }
            // 轉換為一般file 文件
            multipartFile.transferTo(file);
         
            return file;
        } catch (IOException e) {
    
            e.printStackTrace();
            return null;
        }

    }

    /**
     * @return List<List<String>>
     * @Description 讀取CSV文件的內容(不含表頭)
     * @Param filePath 文件存儲路徑,colNum 列數
     **/
    public static List<List<String>> readCSV(String filePath, int colNum) {
        BufferedReader bufferedReader = null;
        InputStreamReader inputStreamReader = null;
        FileInputStream fileInputStream = null;

        try {
            fileInputStream = new FileInputStream(filePath);
            inputStreamReader = new InputStreamReader(fileInputStream);
            bufferedReader = new BufferedReader(inputStreamReader);

            CSVParser parser = CSVFormat.DEFAULT.parse(bufferedReader);


            //  表內容集合,外層 List為行的集合,內層 List為字段集合
            List<List<String>> values = new ArrayList<>();


            int rowIndex = 0;
            // 讀取文件每行內容

            for (CSVRecord record : parser.getRecords()) {
                //  跳過表頭
                if (rowIndex == 0) {
                    rowIndex++;
                    continue;
                }
                // 判斷下角標是否越界
                if(colNum>record.size()){
                    // 返回空集合
                    return values;
                }
                //  每行的內容
                List<String> value = new ArrayList<>();
                for (int i = 0; i < colNum; i++) {
                    value.add(record.get(i));
                }
                values.add(value);
                rowIndex++;
            }
            return values;
        } catch (IOException e) {
            e.printStackTrace();
          
        }finally {
            //關閉流
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStreamReader != null) {
                try {
                    inputStreamReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
}

controller 層java類

@Api(value = "后台考勤管理模塊")  //Swagger測試文件
@CrossOrigin                    // 關於跨域
@RestController                 // 表明為Controller層
@RequestMapping("/admin/attendance")  // url請求路徑
public class AttendanceAdminController {

    @Autowired
    AttendanceService attendanceService;

    @ApiOperation(value = "后台出勤信息Csv批量導入")
    @PostMapping("/csv/import/{month}")
    public R csvImport(
            @ApiParam(name = "month",value = "月份",required = true)
            @PathVariable String month,

            @ApiParam(name = "file", value = "Csv文件",required = true)
            @RequestParam MultipartFile file ){
        // 使用CSV工具類,生成file文件
        File csvFile = CsvImportUtil.uploadFile(file);
        // 將文件內容解析,存入List容器,List<String>為每一行內容的集合,20為CSV文件每行的總列數
        List<List<String>> lists = CsvImportUtil.readCSV(csvFile.getPath(), 20);

        if (lists.size()<1){
            return R.error().message("上傳失敗").data("errorMsg","文件內容為空或模板不對");
        }
        List<String> errorMsg = attendanceService.csvImport(month,lists);
        // 刪 除文件
        csvFile.delete();
        if (errorMsg.size()==0){
            return R.ok().message("文件上傳成功");
        }

        return R.error().message("上傳失敗").data("errorMsg",errorMsg);

    }
}

后邊service層和mapper層代碼就不贅述了,因為功能和需求不同,寫法就不一樣,重點是CSV文件接收和解析,並將數據存入List容器使用。


免責聲明!

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



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