一、依賴引入
1
2
3
4
5
|
<dependency> <groupid>net.sourceforge.jexcelapi</groupid> <artifactid>jxl</artifactid> <version> 2.6 . 12 </version> </dependency> |
二、表格操作
1、讀取xls文件
測(cè)試文件為:
代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
public void test() throws ioexception, biffexception { // 1、獲取文件,創(chuàng)建workbook file file = new file( "d:/test/自動(dòng)化監(jiān)測(cè)數(shù)據(jù)上傳模板20210525.xls" ); workbook workbook = workbook.getworkbook(file); // 2.獲取第一個(gè)工作表 sheet sheet = workbook.getsheet( 0 ); // 3.獲取表中數(shù)據(jù) range[] rangecell = sheet.getmergedcells(); system.out.println( "行:" + sheet.getrows()); system.out.println( "列:" + sheet.getcolumns()); for ( int i = 0 ; i < sheet.getrows(); i++) { for ( int j = 0 ; j < sheet.getcolumns(); j++) { cell cell = sheet.getcell(j, i); string contents = cell.getcontents(); system.out.print(contents + " " ); } system.out.println(); } workbook.close(); } |
輸出結(jié)果(注意合并單元格處,需要特殊處理):
改造代碼如下:
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
|
public void test() throws ioexception, biffexception { // 1、獲取文件,創(chuàng)建workbook file file = new file( "d:/test/自動(dòng)化監(jiān)測(cè)數(shù)據(jù)上傳模板20210525.xls" ); workbook workbook = workbook.getworkbook(file); // 2.獲取第一個(gè)工作表 sheet sheet = workbook.getsheet( 0 ); // 3.獲取表中數(shù)據(jù) // 返回合并單元格數(shù)據(jù) range[] rangecell = sheet.getmergedcells(); system.out.println( "行:" + sheet.getrows()); system.out.println( "列:" + sheet.getcolumns()); for ( int i = 0 ; i < sheet.getrows(); i++) { for ( int j = 0 ; j < sheet.getcolumns(); j++) { cell cell = sheet.getcell(j, i); string contents = cell.getcontents(); // 判斷當(dāng)前單元格,是否為合并單元格 for (range r : rangecell) { if (i > r.gettopleft().getrow() && i <= r.getbottomright().getrow() && j >= r.gettopleft().getcolumn() && j <= r.getbottomright().getcolumn()) { contents = sheet.getcell(r.gettopleft().getcolumn(), r.gettopleft().getrow()).getcontents(); } } system.out.print(contents + " " ); } system.out.println(); } workbook.close(); } |
結(jié)果:
到此這篇關(guān)于java實(shí)現(xiàn)對(duì)excel文件的處理合并單元格的文章就介紹到這了,更多相關(guān)java excel文件合并單元格內(nèi)容請(qǐng)搜索服務(wù)器之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持服務(wù)器之家!
原文鏈接:https://blog.csdn.net/asdhls/article/details/118972285