問題描述
現需要批量導入數據,數據以Excel
形式導入。
POI介紹
我選擇使用的是apache POI
。這是有Apache軟件基金會
開放的函數庫,他會提供API給java,使其可以對office文件進行讀寫。
我這裏只需要使用其中的Excel
部分。
實現
首先,Excel
有兩種格式,一種是.xls(03版)
,另一種是.xlsx(07版)
。針對兩種不同的表格格式,POI
對應提供了兩種接口。HSSFWorkbook
和XSSFWorkbook
導入依賴
<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的版本
,根據擴展名,用不同的類來處理文件。
獲取表格數據
獲取表格中的數據分爲以下幾步:
1.獲取表格
2.獲取某一行
3.獲取這一行中的某個單元格
代碼實現:
// 獲取第一個張表
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();
}
持久化
獲取出單元格中的數據後,最後就是用數據建立對象了。
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...