Java POI實現將導入Excel文件的示例代碼
問題描述
現需要批量導入數據,數據以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);
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
基于Eclipse 的JSP/Servlet的開發(fā)環(huán)境的搭建(圖文)
本文將會詳細地展示如何搭建JSP的開發(fā)環(huán)境。本次教程使用的是最新版的Eclipse 2018-09編輯器和最新版的Apache Tomcat v9.0,步驟詳細,內容詳盡,適合零基礎學者作為學習參考2018-12-12

