好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

java实现对excel文件的处理合并单元格的操作

一、依赖引入

?

1

2

3

4

5

<dependency>

     <groupid>net.sourceforge.jexcelapi</groupid>

     <artifactid>jxl</artifactid>

     <version> 2.6 . 12 </version>

</dependency>

二、表格操作

1、读取xls文件

测试文件为:

代码:

?

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、获取文件,创建workbook

         file file = new file( "d:/test/自动化监测数据上传模板20210525.xls" );

         workbook workbook = workbook.getworkbook(file);

         // 2.获取第一个工作表

         sheet sheet = workbook.getsheet( 0 );

         // 3.获取表中数据

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

     }

输出结果(注意合并单元格处,需要特殊处理):

改造代码如下:

?

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、获取文件,创建workbook

         file file = new file( "d:/test/自动化监测数据上传模板20210525.xls" );

         workbook workbook = workbook.getworkbook(file);

         // 2.获取第一个工作表

         sheet sheet = workbook.getsheet( 0 );

         // 3.获取表中数据

         // 返回合并单元格数据

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

                 // 判断当前单元格,是否为合并单元格

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

     }

结果:

到此这篇关于java实现对excel文件的处理合并单元格的文章就介绍到这了,更多相关java excel文件合并单元格内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

原文链接:https://blog.csdn.net/asdhls/article/details/118972285

查看更多关于java实现对excel文件的处理合并单元格的操作的详细内容...

  阅读:13次