POI實現將導入Excel文件

問題描述

現須要批量導入數據,數據以Excel形式導入。html

POI介紹

我選擇使用的是apache POI。這是有Apache軟件基金會開放的函數庫,他會提供API給java,使其能夠對office文件進行讀寫。java

我這裏只須要使用其中的Excel部分。apache

實現

首先,Excel有兩種格式,一種是.xls(03版),另外一種是.xlsx(07版)。針對兩種不一樣的表格格式,POI對應提供了兩種接口。HSSFWorkbookXSSFWorkbookide

導入依賴

<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

相關文章
相關標籤/搜索