现须要批量导入数据,数据以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