Import database POI + SpringMvc

Scenario:

         Background excel file data upload web page, java backend interface excel converted to the collection, specific business operations, for example batch import database;

1.maven dependence

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.13</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>3.13</version>
</dependency>

2.utils class

/ ** 
 * reads EXCEL file 
 * 
 * @param fielName 
 * @return 
 * / 
public List <String> getExcelInfo (String fileName, MultipartFile Mfile) { 
   // file upload spring convert into MultipartFile File 
   CommonsMultipartFile = CF2 (CommonsMultipartFile) Mfile ; 
   DiskFileItem fi = (DiskFileItem) cf.getFileItem (); 
   file file = fi.getStoreLocation (); 
   List <String> = userList new new ArrayList <String> (); 
   InputStream IS = null; 
   the try { 
      // verify that the file name is qualified 
      {IF (validateExcel (fileName)!) 
         return null; 
      } 
      // when the judge file 2003 version or the 2007 version 
      boolean isExcel2003 = true;
      if (WDWUtil.isExcel2007(fileName)) {
         isExcel2003 = false;
      }
      is = new FileInputStream(file);
      userList = getExcelInfo(is, isExcel2003);
      is.close();
   }
   catch (Exception e) {
      log.getLogger("excelUtil_s").error("getExcelInfo-ex", e.getMessage());
      // e.printStackTrace();
   }
   finally {
      if (is != null) {
         try {
            is.close();
         }
         catch (IOException e) {
            is = null;
            log.getLogger("excelUtil_s").error("FileInputStream-close-fail", e.getMessage());
            // e.printStackTrace ();
         }
      }
   }
   return userList;
}

public List<String> getExcelInfo(InputStream is, boolean isExcel2003) {
   List<String> userList = null;
   try {
      Workbook wb = null;
      // 当excel是2003时
      if (isExcel2003) {
         wb = new HSSFWorkbook(is);
      }
      else {
         wb = new XSSFWorkbook(is);
      }
      userList = readExcelValue(wb);
   }
   catch (IOException e) {
      log.getLogger("excelUtil_s").error("readExcel-IOException", e.getMessage());
      // e.printStackTrace();
   }
   return userList;
}

/**
 * 获取Excel的信息:行和列
 * 
 * @param wb
 * @return
 */
private List<String> readExcelValue(Workbook wb) {
   // 得到第一个shell
   Sheet sheet = wb.getSheetAt(0);
   // 得到Excel的行数
   this.totalRows = sheet.getPhysicalNumberOfRows();
   // 得到Excel的列数(前提是有行数)
   if (totalRows >= 1 && sheet.getRow(0) != null) {
      this.totalCells = sheet.getRow(0).getPhysicalNumberOfCells();
   }
   List<String> userList = new ArrayList<String>();
   String String;
   // 循环row:行
   for (int r = 1; r < totalRows; r++) {
      Row row = sheet.getRow(r);
      if (row == null)
         continue;
      // String = new String();
      // for (int c = 0; c < this.totalCells; c++) {
      // Cell cell = row.getCell(c);
      // if (null != cell) {
      // // 第一列
      // if (c == 0) {
      // String.setUserName(cell.getStringCellValue());
      // }
      // else if (c == 1) {
      // DecimalFormat df = new DecimalFormat("#");
      // String cellValue = df.format(cell.getNumericCellValue());
      // String.setUserNumber(cellValue);
      // }
      // }
      // }
      // 循环每个row的cell:列,本次业务只有一列
      for (int c = 0; c < this.totalCells; c++) {
         Cell cell = row.getCell(c);
         if (null != cell) {
            // first column
            if (c == 0 && !"".equals(cell.getStringCellValue())) {
               userList.add (cell.getStringCellValue ()); // get the string value in the cell (cell providing access to various types of API) 
            } 
         } 
         BREAK; 
      } 
   } 
   return userList; 
}
/ ** 
 * Verify EXCEL file 
 * 
 * @param filePath 
 * @return 
 * / 
public boolean validateExcel (String filePath) { 
   IF (filePath == null ||! (WDWUtil.isExcel2003 (filePath) || WDWUtil.isExcel2007 (filePath)) ) { 
      errorMsg = "filename is not excel format"; 
      return to false; 
   } 
   return to true; 
}
// excel 2003
public static boolean isExcel2003(String filePath) {
   return filePath.matches("^.+\\.(?i)(xls)$");
}

// excel 2007
public static boolean isExcel2007(String filePath) {
   return filePath.matches("^.+\\.(?i)(xlsx)$");
}
private int totalRows = 0;
private int totalCells = 0;
private String errorMsg;
public ReadExcelUtil() {
}

public int getTotalRows() {
   return totalRows;
}

public void setTotalRows(int totalRows) {
   this.totalRows = totalRows;
}

public int getTotalCells() {
   return totalCells;
}

public void setTotalCells(int totalCells) {
   this.totalCells = totalCells;
}

public String getErrorMsg() {
   return errorMsg;
}

public void setErrorMsg(String errorMsg) {
   this.errorMsg = errorMsg;
}

3.test

1)postman

2) controller layer

/ **
     * bulk import data
     *
     * @param headerKey delivery product code number, file import inputFile
     * @param Request
     * @return
     * /
    @RequestMapping (value = "/import.ctrl", Produces = "file application / JSON")
    @ResponseBody
    public void importCode (Long headerKey @RequestParam, @RequestParam (= required to true) a MultipartFile inputFile, the HttpServletRequest Request) {
        pickCodeService.batchInputCode (inputFile, Request, headerKey);
    }

3) to achieve specific business service

public Map<String, Object> batchInputCode(MultipartFile inputFile, HttpServletRequest request, Long headerKey) {
   Map<String, Object> response = Maps.newHashMap();
   List<String> excel_list = Lists.newArrayList();
   excel_list = this.excelIntoList(inputFile);
   if (excel_list != null && excel_list.size() > 0) {
     //使用获取的数据执行数据库操作
   }
   response.put("status", "success");
   return response;
}

4. Reference article: https://blog.csdn.net/m0_37527542/article/details/74542587

 

Guess you like

Origin blog.csdn.net/weixin_37794901/article/details/90786799