前言
本文主要給大家介紹了關于java poi導入excel通用工具類的相關內容,分享出來供大家參考學習,下面話不多說了,來一起看看詳細的介紹吧。
問題引入和分析
提示:如果不想看羅嗦的文章,可以直接到最后點擊源碼下載運行即可
最近在做一個導入excel的功能,在做之前在百度上面查找“java通用導入excel工具類”,沒有查到,大多數都是java通用導出excel。后來仔細想想,導出可以利用java的反射,做成通用的,放進相應的實體成員變量中,導入為什么不可以呢?也是可以的,不過在做之前我們要解決如下兩個問題:
1.表格中的列數和順序要和實體類中的成員變量個數和順序一致。
2.表格中的列的類型要和成員變量的類型一致。
第一個問題:
列數一致可以做到,但是我們最后都是要插入數據庫的。那么id是必不可少的,或者良好的習慣可能還有創建時間,創建人等信息。
所以我想到了兩個辦法:
1.封裝一個vo,只將需要的字段封裝進去,并且字段順序和表格列的順序一致,再將vo與實體類po轉化(用propertyutil.copy
方法);
2.在需要的成員變量上注入自定義注解,并且加入注解的這些字段順序和表格列的順序一致,利用反射得到這些字段。
這里主要利用第二個方法,因為擴展性更好
第二個問題:
獲取表格數據的時候,我們要判斷類型,并取得相應值,全部轉化為string類型,當我們給實體類賦值的時候,利用反射獲取需要的成員變量的類型,并賦值。
需求
假設我們需求的excel如下:
我們可以看做兩部分:
第一部分:
第二行到第11行,為一個列表數據,共有字段5個,分別為:學號,姓名,身份證號碼,性別,分數
第二部分:
第12行第五列,第12行第六列,共有字段2個,分別為:總計,平均
項目
需要導入的jar包
1.poi的相關jar包,主要用來處理excel
2.beanutils 利用反射為成員變量賦值
3.commons-lang string判斷非空的方法,可以不用自己判斷
如若maven項目導入下面的jar包
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
<!-- poi操作excel --> <dependency> <groupid>org.apache.poi</groupid> <artifactid>poi-ooxml</artifactid> <version> 3.8 </version> </dependency> <dependency> <groupid>org.apache.poi</groupid> <artifactid>poi</artifactid> <version> 3.8 </version> </dependency> <dependency> <groupid>org.apache.poi</groupid> <artifactid>poi-ooxml-schemas</artifactid> <version> 3.8 </version> </dependency> <!-- beanutils --> <dependency> <groupid>commons-beanutils</groupid> <artifactid>commons-beanutils</artifactid> <version> 1.8 . 3 </version> </dependency> <!-- commons-lang--> <dependency> <groupid>commons-lang</groupid> <artifactid>commons-lang</artifactid> <version> 2.6 </version> </dependency> |
非maven項目導入下面的jar(下面例子當中用到的jar,有些沒用到,可自行處理)
1
2
3
4
5
6
7
8
9
10
11
12
|
commons-beanutils- 1.8 . 3 .jar commons-lang- 2.6 .jar commons-logging- 1.1 .jar dom4j- 1.6 . 1 .jar log4j- 1.2 . 13 .jar poi- 3.8 - 20120326 .jar poi-excelant- 3.8 - 20120326 .jar poi-ooxml- 3.8 - 20120326 .jar poi-ooxml-schemas- 3.8 - 20120326 .jar poi-scratchpad- 3.8 - 20120326 .jar stax-api- 1.0 . 1 .jar xmlbeans- 2.3 . 0 .jar |
項目結構
工具類
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
|
package com.dao.chu.excel; import java.io.ioexception; import java.io.inputstream; import java.lang.reflect.field; import java.math.bigdecimal; import java.text.decimalformat; import java.text.parseexception; import java.text.simpledateformat; import java.util.arraylist; import java.util.date; import java.util.list; import java.util.locale; import org.apache.commons.beanutils.propertyutils; import org.apache.commons.lang.stringutils; import org.apache.poi.hssf.usermodel.hssfcell; import org.apache.poi.hssf.usermodel.hssfworkbook; import org.apache.poi.ss.usermodel.cell; import org.apache.poi.ss.usermodel.row; import org.apache.poi.ss.usermodel.sheet; import org.apache.poi.ss.usermodel.workbook; import org.apache.poi.xssf.usermodel.xssfworkbook; /** * * excel讀取工具類 * * @author daochuwenziyao * @see [相關類/方法] * @since [產品/模塊版本] */ public class importexeclutil { private static int totalrows = 0 ; // 總行數 private static int totalcells = 0 ; // 總列數 private static string errorinfo; // 錯誤信息 /** 無參構造方法 */ public importexeclutil() { } public static int gettotalrows() { return totalrows; } public static int gettotalcells() { return totalcells; } public static string geterrorinfo() { return errorinfo; } /** * * 根據流讀取excel文件 * * * @param inputstream * @param isexcel2003 * @return * @see [類、類#方法、類#成員] */ public list<list<string>> read(inputstream inputstream, boolean isexcel2003) throws ioexception { list<list<string>> datalst = null ; /** 根據版本選擇創建workbook的方式 */ workbook wb = null ; if (isexcel2003) { wb = new hssfworkbook(inputstream); } else { wb = new xssfworkbook(inputstream); } datalst = readdate(wb); return datalst; } /** * * 讀取數據 * * @param wb * @return * @see [類、類#方法、類#成員] */ private list<list<string>> readdate(workbook wb) { list<list<string>> datalst = new arraylist<list<string>>(); /** 得到第一個shell */ sheet sheet = wb.getsheetat( 0 ); /** 得到excel的行數 */ totalrows = sheet.getphysicalnumberofrows(); /** 得到excel的列數 */ if (totalrows >= 1 && sheet.getrow( 0 ) != null ) { totalcells = sheet.getrow( 0 ).getphysicalnumberofcells(); } /** 循環excel的行 */ for ( int r = 0 ; r < totalrows; r++) { row row = sheet.getrow(r); if (row == null ) { continue ; } list<string> rowlst = new arraylist<string>(); /** 循環excel的列 */ for ( int c = 0 ; c < gettotalcells(); c++) { cell cell = row.getcell(c); string cellvalue = "" ; if ( null != cell) { // 以下是判斷數據的類型 switch (cell.getcelltype()) { case hssfcell.cell_type_numeric: // 數字 cellvalue = cell.getnumericcellvalue() + "" ; break ; case hssfcell.cell_type_string: // 字符串 cellvalue = cell.getstringcellvalue(); break ; case hssfcell.cell_type_boolean: // boolean cellvalue = cell.getbooleancellvalue() + "" ; break ; case hssfcell.cell_type_formula: // 公式 cellvalue = cell.getcellformula() + "" ; break ; case hssfcell.cell_type_blank: // 空值 cellvalue = "" ; break ; case hssfcell.cell_type_error: // 故障 cellvalue = "非法字符" ; break ; default : cellvalue = "未知類型" ; break ; } } rowlst.add(cellvalue); } /** 保存第r行的第c列 */ datalst.add(rowlst); } return datalst; } /** * * 按指定坐標讀取實體數據 * <按順序放入帶有注解的實體成員變量中> * * @param wb 工作簿 * @param t 實體 * @param in 輸入流 * @param integers 指定需要解析的坐標 * @return t 相應實體 * @throws ioexception * @throws exception * @see [類、類#方法、類#成員] */ @suppresswarnings ( "unused" ) public static <t> t readdatet(workbook wb, t t, inputstream in, integer[]... integers) throws ioexception, exception { // 獲取該工作表中的第一個工作表 sheet sheet = wb.getsheetat( 0 ); // 成員變量的值 object entitymembervalue = "" ; // 所有成員變量 field[] fields = t.getclass().getdeclaredfields(); // 列開始下標 int startcell = 0 ; /** 循環出需要的成員 */ for ( int f = 0 ; f < fields.length; f++) { fields[f].setaccessible( true ); string fieldname = fields[f].getname(); boolean fieldhasanno = fields[f].isannotationpresent(isneeded. class ); // 有注解 if (fieldhasanno) { isneeded annotation = fields[f].getannotation(isneeded. class ); boolean isneeded = annotation.isneeded(); // excel需要賦值的列 if (isneeded) { // 獲取行和列 int x = integers[startcell][ 0 ] - 1 ; int y = integers[startcell][ 1 ] - 1 ; row row = sheet.getrow(x); cell cell = row.getcell(y); if (row == null ) { continue ; } // excel中解析的值 string cellvalue = getcellvalue(cell); // 需要賦給成員變量的值 entitymembervalue = getentitymembervalue(entitymembervalue, fields, f, cellvalue); // 賦值 propertyutils.setproperty(t, fieldname, entitymembervalue); // 列的下標加1 startcell++; } } } return t; } /** * * 讀取列表數據 * <按順序放入帶有注解的實體成員變量中> * * @param wb 工作簿 * @param t 實體 * @param beginline 開始行數 * @param totalcut 結束行數減去相應行數 * @return list<t> 實體列表 * @throws exception * @see [類、類#方法、類#成員] */ @suppresswarnings ( "unchecked" ) public static <t> list<t> readdatelistt(workbook wb, t t, int beginline, int totalcut) throws exception { list<t> listt = new arraylist<t>(); /** 得到第一個shell */ sheet sheet = wb.getsheetat( 0 ); /** 得到excel的行數 */ totalrows = sheet.getphysicalnumberofrows(); /** 得到excel的列數 */ if (totalrows >= 1 && sheet.getrow( 0 ) != null ) { totalcells = sheet.getrow( 0 ).getphysicalnumberofcells(); } /** 循環excel的行 */ for ( int r = beginline - 1 ; r < totalrows - totalcut; r++) { object newinstance = t.getclass().newinstance(); row row = sheet.getrow(r); if (row == null ) { continue ; } // 成員變量的值 object entitymembervalue = "" ; // 所有成員變量 field[] fields = t.getclass().getdeclaredfields(); // 列開始下標 int startcell = 0 ; for ( int f = 0 ; f < fields.length; f++) { fields[f].setaccessible( true ); string fieldname = fields[f].getname(); boolean fieldhasanno = fields[f].isannotationpresent(isneeded. class ); // 有注解 if (fieldhasanno) { isneeded annotation = fields[f].getannotation(isneeded. class ); boolean isneeded = annotation.isneeded(); // excel需要賦值的列 if (isneeded) { cell cell = row.getcell(startcell); string cellvalue = getcellvalue(cell); entitymembervalue = getentitymembervalue(entitymembervalue, fields, f, cellvalue); // 賦值 propertyutils.setproperty(newinstance, fieldname, entitymembervalue); // 列的下標加1 startcell++; } } } listt.add((t)newinstance); } return listt; } /** * * 根據excel表格中的數據判斷類型得到值 * * @param cell * @return * @see [類、類#方法、類#成員] */ private static string getcellvalue(cell cell) { string cellvalue = "" ; if ( null != cell) { // 以下是判斷數據的類型 switch (cell.getcelltype()) { case hssfcell.cell_type_numeric: // 數字 if (org.apache.poi.ss.usermodel.dateutil.iscelldateformatted(cell)) { date thedate = cell.getdatecellvalue(); simpledateformat dff = new simpledateformat( "yyyy-mm-dd" ); cellvalue = dff.format(thedate); } else { decimalformat df = new decimalformat( "0" ); cellvalue = df.format(cell.getnumericcellvalue()); } break ; case hssfcell.cell_type_string: // 字符串 cellvalue = cell.getstringcellvalue(); break ; case hssfcell.cell_type_boolean: // boolean cellvalue = cell.getbooleancellvalue() + "" ; break ; case hssfcell.cell_type_formula: // 公式 cellvalue = cell.getcellformula() + "" ; break ; case hssfcell.cell_type_blank: // 空值 cellvalue = "" ; break ; case hssfcell.cell_type_error: // 故障 cellvalue = "非法字符" ; break ; default : cellvalue = "未知類型" ; break ; } } return cellvalue; } /** * * 根據實體成員變量的類型得到成員變量的值 * * @param realvalue * @param fields * @param f * @param cellvalue * @return * @see [類、類#方法、類#成員] */ private static object getentitymembervalue(object realvalue, field[] fields, int f, string cellvalue) { string type = fields[f].gettype().getname(); switch (type) { case "char" : case "java.lang.character" : case "java.lang.string" : realvalue = cellvalue; break ; case "java.util.date" : realvalue = stringutils.isblank(cellvalue) ? null : dateutil.strtodate(cellvalue, dateutil.yyyy_mm_dd); break ; case "java.lang.integer" : realvalue = stringutils.isblank(cellvalue) ? null : integer.valueof(cellvalue); break ; case "int" : case "float" : case "double" : case "java.lang.double" : case "java.lang.float" : case "java.lang.long" : case "java.lang.short" : case "java.math.bigdecimal" : realvalue = stringutils.isblank(cellvalue) ? null : new bigdecimal(cellvalue); break ; default : break ; } return realvalue; } /** * * 根據路徑或文件名選擇excel版本 * * * @param filepathorname * @param in * @return * @throws ioexception * @see [類、類#方法、類#成員] */ public static workbook chooseworkbook(string filepathorname, inputstream in) throws ioexception { /** 根據版本選擇創建workbook的方式 */ workbook wb = null ; boolean isexcel2003 = excelversionutil.isexcel2003(filepathorname); if (isexcel2003) { wb = new hssfworkbook(in); } else { wb = new xssfworkbook(in); } return wb; } static class excelversionutil { /** * * 是否是2003的excel,返回true是2003 * * * @param filepath * @return * @see [類、類#方法、類#成員] */ public static boolean isexcel2003(string filepath) { return filepath.matches( "^.+\\.(?i)(xls)$" ); } /** * * 是否是2007的excel,返回true是2007 * * * @param filepath * @return * @see [類、類#方法、類#成員] */ public static boolean isexcel2007(string filepath) { return filepath.matches( "^.+\\.(?i)(xlsx)$" ); } } public static class dateutil { // ======================日期格式化常量=====================// public static final string yyyy_mm_ddhhmmss = "yyyy-mm-dd hh:mm:ss" ; public static final string yyyy_mm_dd = "yyyy-mm-dd" ; public static final string yyyy_mm = "yyyy-mm" ; public static final string yyyy = "yyyy" ; public static final string yyyymmddhhmmss = "yyyymmddhhmmss" ; public static final string yyyymmdd = "yyyymmdd" ; public static final string yyyymm = "yyyymm" ; public static final string yyyymmddhhmmss_1 = "yyyy/mm/dd hh:mm:ss" ; public static final string yyyy_mm_dd_1 = "yyyy/mm/dd" ; public static final string yyyy_mm_1 = "yyyy/mm" ; /** * * 自定義取值,date類型轉為string類型 * * @param date 日期 * @param pattern 格式化常量 * @return * @see [類、類#方法、類#成員] */ public static string datetostr(date date, string pattern) { simpledateformat format = null ; if ( null == date) return null ; format = new simpledateformat(pattern, locale.getdefault()); return format.format(date); } /** * 將字符串轉換成date類型的時間 * <hr> * * @param s 日期類型的字符串<br> * datepattern :yyyy_mm_dd<br> * @return java.util.date */ public static date strtodate(string s, string pattern) { if (s == null ) { return null ; } date date = null ; simpledateformat sdf = new simpledateformat(pattern); try { date = sdf.parse(s); } catch (parseexception e) { e.printstacktrace(); } return date; } } } |
自定義注解
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
import java.lang.annotation.elementtype; import java.lang.annotation.retention; import java.lang.annotation.retentionpolicy; import java.lang.annotation.target; /** * * 是否需要從解析excel賦值 * @author daochuwenziyao * @see [相關類/方法] * @since [產品/模塊版本] */ @retention (value = retentionpolicy.runtime) @target (value = {elementtype.field}) public @interface isneeded { /** * 是否需要從解析excel賦值 * @return * true:需要 false:不需要 * @see [類、類#方法、類#成員] */ boolean isneeded() default true ; } |
學生基本信息
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
|
import java.math.bigdecimal; /** * * 學生基本信息 * @author daochuwenziyao * @see [相關類/方法] * @since [產品/模塊版本] */ public class studentbaseinfo { private integer id; @isneeded private string no; @isneeded private string name; @isneeded private string idnum; @isneeded private string sex; @isneeded private bigdecimal grade; @override public string tostring() { return "studentbaseinfo [id=" + id + ", no=" + no + ", name=" + name + ", idnum=" + idnum + ", sex=" + sex + ", grade=" + grade + "]" ; } public integer getid() { return id; } public void setid(integer id) { this .id = id; } public string getno() { return no; } public void setno(string no) { this .no = no; } public string getname() { return name; } public void setname(string name) { this .name = name; } public string getsex() { return sex; } public void setsex(string sex) { this .sex = sex; } public string getidnum() { return idnum; } public void setidnum(string idnum) { this .idnum = idnum; } public bigdecimal getgrade() { return grade; } public void setgrade(bigdecimal grade) { this .grade = grade; } } |
學生統計信息
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
|
/** * * 學生統計信息 * @author daochuwenziyao * @see [相關類/方法] * @since [產品/模塊版本] */ public class studentstatistics { private integer id; @isneeded private bigdecimal totalgrade; @isneeded private bigdecimal avggrade; @override public string tostring() { return "studentstatistics [id=" + id + ", totalgrade=" + totalgrade + ", avggrade=" + avggrade + "]" ; } public integer getid() { return id; } public void setid(integer id) { this .id = id; } public bigdecimal gettotalgrade() { return totalgrade; } public void settotalgrade(bigdecimal totalgrade) { this .totalgrade = totalgrade; } public bigdecimal getavggrade() { return avggrade; } public void setavggrade(bigdecimal avggrade) { this .avggrade = avggrade; } } |
測試類
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
|
package com.dao.chu.excel; import java.io.file; import java.io.fileinputstream; import java.io.ioexception; import java.io.inputstream; import java.util.list; import org.apache.poi.ss.usermodel.workbook; public class testimportexcel { public static void main(string[] args) throws ioexception, exception { string filename= "student.xlsx" ; inputstream in = new fileinputstream( new file( "excelfile\\student.xlsx" )); workbook wb = importexeclutil.chooseworkbook(filename, in); studentstatistics studentstatistics = new studentstatistics(); //讀取一個對象的信息 studentstatistics readdatet = importexeclutil.readdatet(wb, studentstatistics, in, new integer[] { 12 , 5 }, new integer[] { 13 , 5 }); system.out.println(readdatet); //讀取對象列表的信息 studentbaseinfo studentbaseinfo = new studentbaseinfo(); //第二行開始,到倒數第三行結束(總數減去兩行) list<studentbaseinfo> readdatelistt = importexeclutil.readdatelistt(wb, studentbaseinfo, 2 , 2 ); system.out.println(readdatelistt); } } |
輸出結果
1
2
|
studentstatistics [id= null , totalgrade= 845 , avggrade= 84 ] [studentbaseinfo [id= null , no= 2012240001 , name=張三 1 , idnum= 233314199009062304 , sex=男, grade= 80 ], studentbaseinfo [id= null , no= 2012240002 , name=張三 2 , idnum= 233314199009062304 , sex=男, grade= 81 ], studentbaseinfo [id= null , no= 2012240003 , name=張三 3 , idnum= 233314199009062304 , sex=男, grade= 82 ], studentbaseinfo [id= null , no= 2012240004 , name=張三 4 , idnum= 233314199009062304 , sex=男, grade= 83 ], studentbaseinfo [id= null , no= 2012240005 , name=張三 5 , idnum= 233314199009062304 , sex=男, grade= 84 ], studentbaseinfo [id= null , no= 2012240006 , name=張三 6 , idnum= 233314199009062304 , sex=男, grade= 85 ], studentbaseinfo [id= null , no= 2012240007 , name=張三 7 , idnum= 233314199009062304 , sex=男, grade= 86 ], studentbaseinfo [id= null , no= 2012240008 , name=張三 8 , idnum= 233314199009062304 , sex=男, grade= 87 ], studentbaseinfo [id= null , no= 2012240009 , name=張三 9 , idnum= 233314199009062304 , sex=男, grade= 88 ], studentbaseinfo [id= null , no= 2012240010 , name=張三 10 , idnum= 233314199009062304 , sex=男, grade= 89 ]] |
源碼下載
源碼分享給大家,上面提到的都在這里,由于很多的數據類型沒有試驗到,可能會有些類型有問題,所以希望大家如果遇到問題回復我,我會將其完善。
源碼下載:importexcelutil.rar
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對服務器之家的支持。
原文鏈接:http://blog.csdn.net/daochuwenziyao/article/details/77914826