小白今天閒着沒事,在公司摸魚,覺得今天有事無聊的一天,忽然上頭說小子,今天實現一下批量導入Excel數據吧,當時個人心裏是拒絕的,而後默默打開idea。java
java自己並不支持讀取excel,全部讀取excel須要藉助一些框架。目前有幾種方式,spring
1. Apache POIsql
2. Java Excel APIspringboot
3. easyexcelapp
這裏主要講解的是 Apache POI,Apache POI支持03版以及07年版 區別是後綴不同,03版對應的是xls 07版對應的是xlsx xlsx
這裏主要講解的是07版的框架
1.sheet表示的是xss
excel底部的工做表.ide
對應的是POI的的XSSFSheetui
2.row表示的是行idea
對應的是POI的的XSSFRow
3.cell表示的是每一行的單元格.
對應的是POI的的Cell
1.上傳文件使用springboot的MultipartFile
對應
MultipartFile file
2.建立對象
XSSFWorkbook xssfWorkbook = new XSSFWorkbook(inputStream);
3.獲取sheet(默認第一個)
XSSFSheet sheet = xssfWorkbook.getSheetAt(0);
@RequestMapping("/import") public void importExcel(@RequestParam("file") MultipartFile file) throws Exception{ InputStream inputStream = file.getInputStream(); //07年的 不兼容以前 XSSFWorkbook xssfWorkbook = new XSSFWorkbook(inputStream); XSSFSheet sheet = xssfWorkbook.getSheetAt(0); //獲取行數 int lastRowNum = sheet.getLastRowNum(); for (int i = 1; i <= lastRowNum; i++) { XSSFRow row = sheet.getRow(i); QuChannel quChannel = new QuChannel(); if (row.getCell(0) != null){ row.getCell(0).setCellType(XSSFCell.CELL_TYPE_STRING); quChannel.setChannel(row.getCell(0).getStringCellValue()); } if (row.getCell(1) != null){ row.getCell(1).setCellType(XSSFCell.CELL_TYPE_STRING); quChannel.setChannelName(row.getCell(1).getStringCellValue()); } if (row.getCell(2) != null){ row.getCell(2).setCellType(XSSFCell.CELL_TYPE_STRING); quChannel.setRemarks(row.getCell(2).getStringCellValue()); } if (row.getCell(3) != null){ quChannel.setChannelSource((int) row.getCell(3).getNumericCellValue()); } if (row.getCell(4) != null){ quChannel.setActivityType((int) row.getCell(4).getNumericCellValue()); } if (row.getCell(5) != null){ quChannel.setDeliveryTime(row.getCell(5).getDateCellValue()); } if (row.getCell(6) != null){ row.getCell(6).setCellType(XSSFCell.CELL_TYPE_STRING); quChannel.setOriginalLink(row.getCell(6).getStringCellValue()); } if (row.getCell(7) != null){ row.getCell(7).setCellType(XSSFCell.CELL_TYPE_STRING); quChannel.setSaLink(row.getCell(7).getStringCellValue()); } if (row.getCell(8) != null){ quChannel.setDeliveryMode((int) row.getCell(8).getNumericCellValue()); } if (row.getCell(9) != null){ quChannel.setCreateGroup((int) row.getCell(9).getNumericCellValue()); } if (row.getCell(10) != null){ row.getCell(10).setCellType(XSSFCell.CELL_TYPE_STRING); quChannel.setRemark(row.getCell(10).getStringCellValue()); } quChannelMapper.insert(quChannel); } }
1.避免將sql寫在for循環裏面,改進的話能夠建立一個列表list,將對象add進去,而後在循環外面進行批量插入
2.想要去重的話可使用set的不能重複添加特性
3.注意excel的字段與類屬性的對應關係,若是excel字段是string,可是累屬性是整形的話,可使用枚舉類
暫時想到這麼多 歡迎指教評論