spring boot mybatis + vue POI implemented using bulk import data from Excel

A front end vue + element

  1. The front-end component element to achieve upload file upload

          <el-upload
                        style="display: inline-flex;margin-right: 8px"
                        :show-file-list="false"  
                        :before-upload="beforeUpload"
                        :on-success="onSuccess"
                        :on-error="onError"
                        accept=".xls"
                        :disabled="importDataButtonDisabled"
                        action="/employee/basic/import">
                    <el-button :disabled="importDataButtonDisabled" type="success" size="small" :icon="importDataButtonIcon">
                        {{importDataButtonMsg}}
                    </el-button>
                </el-upload>

    File-List-Show : whether to display the selected file list

    the Upload-the before : file upload hook before call

    on-error: file upload hook after defeat

    on-success: file upload hook after the success of

    accept: Accepted file types

    action: upload address

  2. The process callback function

 

// bulk import users into two steps: 1. 2. Upload Excel file into the database after the data conversion of Excel 
            // ** Note: upload success callback here only refers to the Excel file upload success, does not mean that the entire bulk import operation of the user is successful 
            the onSuccess (Response, File, the fileList) {
                 // value, and changes the icon callback after successful upload "import data" button shown in 
                the this .importDataButtonMsg = 'import data' ;
                 the this .importDataButtonIcon = ' upload2-icon-EL ' ;
                 the this .importDataButtonDisabled = to false ;
                 // the file upload is successful, the determination result data into the database of employees (also corresponding to the user's operation result bulk import) 
               IF (== 200 is Response.Status ) { 
                   the Message. Success ({Message: response.msg}) 
               } the else  IF(response.status == 500 ) { 
                   Message.Error An ({the Message: response.msg}) 
               } the else { 
                   Message.Error An ({the Message: 'Unknown Error' }) 
               } 
            } 
            // Upload the file failed callbacks to change. " icon button and import data value "display 
            the onError (ERR, File, the fileList) {
                 the this .importDataButtonMsg = 'import data' ;
                 the this .importDataButtonIcon = 'EL-icon-upload2' ;
                 the this .importDataButtonDisabled = to false ;
                 the this . $ Message .error (ERR); 
            }, 
            //Callback Change "Import Data" before the upload button display values and icons so that the user can distinguish the state of buttons 
            beforeUpload () {
                 the this .importDataButtonMsg = 'uploading' ;
                 the this .importDataButtonIcon = 'EL-icon-loading' ;
                 the this .importDataButtonDisabled = to true ; 
            },

 

    Bulk import data into two steps: 1. 2. Excel files uploaded into the database after the data conversion to Excel. 

    In order to prevent duplication of data import click-click the Import button again and senses distinguish not clicked button and click the imported data, and an icon button display value set is introduced for dynamic data by the update button hooks and icons displayed value.

    Note: Uploading success callback here only refers to the Excel file upload success, does not mean that the entire batch import user's operation was successful

 

Second, the rear end of the spring boot + mybatis

  1.controller receiving layer

 @PostMapping("/import")
    public RespBean importEmp(MultipartFile file){
        // 拿到 file 对象
        List<Employee> employees = EmpUtils.excelToObj(file,nationService.getAllNations(),departmentService.getAllDepartmentWithoutChild(),jobLevelService.getAllJobLevels(),
                politicsstatusService.getAllPoliticsstatuss(),positionService.getAllPositions());
       if (employeeService.importEmp(employees) == employees.size()){
        return RespBean.ok("导入成功!");
       }
       return RespBean.error("导入失败!");
    }

  controller receiving layer to receive class files MultipartFile, ignore the other parameters.

  2. Process MultipartFile class object

public static List<Employee> excelToObj(MultipartFile file, List<Nation> allNations, List<Department> allDepartment, List<JobLevel> allJobLevels, 
List<Politicsstatus> allPoliticsstatuss, List<Position> allPositions) { List<Employee> employeeList = new ArrayList<>(); InputStream inputStream = null; try { //1.获取文件的输入流 inputStream = file.getInputStream(); //2.获取Excel工作簿对象 HSSFWorkbook workbook = new HSSFWorkbook(inputStream); //3. Get Excel Worksheet Object because only a worksheet object so the first object can take // if more than one sheet objects can be obtained by the following manner after traversing // int = numberOfSheets workbook.getNumberOfSheets () ; HSSFSheet sheetAt workbook.getSheetAt = (0 ); // 4. cycle read table data for (Row Row: sheetAt) { // header (header) to skip IF (row.getRowNum () == 0 ) { Continue ; } // null skip line IF (row == null ) { Continue ; } the Employee Employee =new new the Employee (); // number of columns in int physicalNumberOfCells = row.getPhysicalNumberOfCells (); for ( int K = 0; K <physicalNumberOfCells; K ++ ) { the Cell Cell = row.getCell (K); // first column of the table by type classified Switch (cell.getCellType ()) { // handle string type Case sTRING: Switch (K) { Case . 1 : employee.setName (cell.getStringCellValue ()); BREAK ; Case 2 : employee.setWorkID (cell.getStringCellValue ()); BREAK ; default : { BREAK ; } } BREAK ; default : { Switch (K) { Case . 4 : // process a date type column employee.setBirthday(cell.getDateCellValue()); break; case 20: employee.setBeginDate(cell.getDateCellValue()); break; case 22: employee.setBeginContract(cell.getDateCellValue()); break; case 23: employee.setEndContract(cell.getDateCellValue()); break; case 24: //处理double类型的列 employee.setContractTerm(cell.getNumericCellValue()); break; case 25: employee.setConversionTime(cell.getDateCellValue()); break; default: break; } break; } } } employeeList.add(employee); } } catch (IOException e) { e.printStackTrace(); } return employeeList; }

     // input stream file 1. Obtain
            inputStream = file.getInputStream ();
            // 2. Get Excel workbook object Workbook = HSSFWorkbook new new HSSFWorkbook (inputStream);
            @ 3. Excel Worksheet Object acquired because only one working table object so the first object to take
            // traverse If multiple worksheet object can be obtained by the following manner
   //  int numberOfSheets workbook.getNumberOfSheets = ();
            HSSFSheet sheetAt = workbook.getSheetAt (0 );
            // 4. the data read table row loop processing

  3. foreach bulk inserts the data mapper.xml mybatis 

 

<insert id="importEmp" parameterType="com.hopec.vhr.bean.Employee">
    insert into employee (name, gender,
      birthday, idCard, wedlock, nationId
      )
      values
      <foreach collection="emps" separator="," item="emp">
        (#{emp.name,jdbcType=VARCHAR}, #{emp.gender,jdbcType=CHAR},
        #{emp.birthday,jdbcType=DATE}, #{emp.idCard,jdbcType=CHAR}, #{emp.wedlock,jdbcType=CHAR}, #{emp.nationId,jdbcType=INTEGER}
        )
      </foreach>
  </insert>

 

  Bulk Insert the return value is the number of records inserted into the database, bulk insert either all succeed, or all fail.

Guess you like

Origin www.cnblogs.com/hopeofthevillage/p/12107870.html