問題描述
現需要批量導入數據,數據以excel形式導入。
poi介紹
我選擇使用的是apache poi。這是有apache軟件基金會開放的函數庫,他會提供api給java,使其可以對office文件進行讀寫。
我這里只需要使用其中的excel部分。
實現
首先,excel有兩種格式,一種是.xls(03版),另一種是.xlsx(07版)。針對兩種不同的表格格式,poi對應提供了兩種接口。hssfworkbook和xssfworkbook
導入依賴
1
2
3
4
5
6
7
8
9
10
|
<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> |
處理版本
1
2
3
4
5
6
7
8
9
10
11
12
13
|
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.獲取這一行中的某個單元格
代碼實現:
1
2
3
4
5
6
7
8
9
10
11
12
|
// 獲取第一個張表 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(); } |
持久化
獲取出單元格中的數據后,最后就是用數據建立對象了。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
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://segmentfault.com/a/1190000018258878