欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Java POI實(shí)現(xiàn)將導(dǎo)入Excel文件的示例代碼

 更新時(shí)間:2019年02月27日 09:17:23   作者:喵先生的進(jìn)階之路  
這篇文章主要介紹了Java POI實(shí)現(xiàn)將導(dǎo)入Excel文件的示例代碼,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧

問(wèn)題描述

現(xiàn)需要批量導(dǎo)入數(shù)據(jù),數(shù)據(jù)以Excel形式導(dǎo)入。

POI介紹

我選擇使用的是apache POI。這是有Apache軟件基金會(huì)開(kāi)放的函數(shù)庫(kù),他會(huì)提供API給java,使其可以對(duì)office文件進(jìn)行讀寫。

我這里只需要使用其中的Excel部分。

實(shí)現(xiàn)

首先,Excel有兩種格式,一種是.xls(03版),另一種是.xlsx(07版)。針對(duì)兩種不同的表格格式,POI對(duì)應(yīng)提供了兩種接口。HSSFWorkbook和XSSFWorkbook

導(dǎo)入依賴

<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的版本,根據(jù)擴(kuò)展名,用不同的類來(lái)處理文件。

獲取表格數(shù)據(jù)

獲取表格中的數(shù)據(jù)分為以下幾步:

1.獲取表格
2.獲取某一行
3.獲取這一行中的某個(gè)單元格

代碼實(shí)現(xiàn):

// 獲取第一個(gè)張表
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();
}

持久化

獲取出單元格中的數(shù)據(jù)后,最后就是用數(shù)據(jù)建立對(duì)象了。

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);

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論