應用場景:
後臺web頁面上傳數據excel文件,java後端接口實現excel轉換到集合中,進行具體業務操作,例批量導入數據庫等;
1.maven依賴
<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類
/** * 讀取EXCEL文件 * * @param fielName * @return */ public List<String> getExcelInfo(String fileName, MultipartFile Mfile) { // 把spring文件上傳的MultipartFile轉換成File CommonsMultipartFile cf = (CommonsMultipartFile) Mfile; DiskFileItem fi = (DiskFileItem) cf.getFileItem(); File file = fi.getStoreLocation(); List<String> userList = new ArrayList<String>(); InputStream is = null; try { // 驗證文件名是否合格 if (!validateExcel(fileName)) { return null; } // 判斷文件時2003版本還是2007版本 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) { // 第一列 if (c == 0 && !"".equals(cell.getStringCellValue())) { userList.add(cell.getStringCellValue());// 獲取cell中的字符串值(cell提供獲取各種類型的api) } } break; } } return userList; }
/** * 驗證EXCEL文件 * * @param filePath * @return */ public boolean validateExcel(String filePath) { if (filePath == null || !(WDWUtil.isExcel2003(filePath) || WDWUtil.isExcel2007(filePath))) { errorMsg = "文件名不是excel格式"; return false; } return 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層
/**
* 批量導入數據
*
* @param headerKey 提貨碼商品編號,inputFile 導入的文件
* @param request
* @return
*/
@RequestMapping(value = "/import.ctrl", produces = "application/json")
@ResponseBody
public void importCode(@RequestParam Long headerKey, @RequestParam(required = true) MultipartFile inputFile, HttpServletRequest request) {
pickCodeService.batchInputCode(inputFile, request, headerKey);
}
3)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.參考文章:https://blog.csdn.net/m0_37527542/article/details/74542587