現須要批量導入數據,數據以Excel
形式導入。html
我選擇使用的是apache POI
。這是有Apache軟件基金會
開放的函數庫,他會提供API給java,使其能夠對office文件進行讀寫。java
我這裏只須要使用其中的Excel
部分。apache
首先,Excel
有兩種格式,一種是.xls(03版)
,另外一種是.xlsx(07版)
。針對兩種不一樣的表格格式,POI
對應提供了兩種接口。HSSFWorkbook
和XSSFWorkbook
ide
<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>RELEASE</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>RELEASE</version> </dependency>
Workbook workbook = null; try { if (file.getPath().endsWith("xls")) { System.out.println("這是2003版本"); workbook = new XSSFWorkbook(new FileInputStream(file)); } else if (file.getPath().endsWith("xlsx")){ workbook = new HSSFWorkbook(new FileInputStream(file)); System.out.println("這是2007版本"); } } catch (IOException e) { e.printStackTrace(); }
這裏須要判斷一下Excel的版本
,根據擴展名,用不一樣的類來處理文件。函數
獲取表格中的數據分爲如下幾步:ui
1.獲取表格
2.獲取某一行
3.獲取這一行中的某個單元格
代碼實現:.net
// 獲取第一個張表 Sheet sheet = workbook.getSheetAt(0); // 獲取每行中的字段 for (int i = 0; i <= sheet.getLastRowNum(); i++) { Row row = sheet.getRow(i); // 獲取行 // 獲取單元格中的值 String studentNum = row.getCell(0).getStringCellValue(); String name = row.getCell(1).getStringCellValue(); String phone = row.getCell(2).getStringCellValue(); }
獲取出單元格中的數據後,最後就是用數據創建對象了。code
List<Student> studentList = new ArrayList<>(); for (int i = 0; i <= sheet.getLastRowNum(); i++) { Row row = sheet.getRow(i); // 獲取行 // 獲取單元格中的值 String studentNum = row.getCell(0).getStringCellValue(); String name = row.getCell(1).getStringCellValue(); String phone = row.getCell(2).getStringCellValue(); Student student = new Student(); student.setStudentNumber(studentNum); student.setName(name); student.setPhoneNumber(phone); studentList.add(student); } // 持久化 studentRepository.saveAll(studentList);
相關參考:
https://poi.apache.org/compon...
https://blog.csdn.net/daihuim...component