最近项目中用到poi生成Excel时,用到了单元格合并,于是参考了http://www.anyrt.com/blog/list/poiexcel.html写的文章,但是其中有些地方不是很清楚,于是自己琢磨了一下,实现了功能,并在此记录一下:
1 int index = 3 ; 2 String lastCell = ""; 3 String thisCell = ""; 4 int lastRowIndex = 0; 5 while(rs.next()){//每行 6 poiExcel.setCellIntValue(0, index, 0, (index-2)); 7 for(int i = 0 ; i<array.length ;i++){//每列 8 colum = array[i]; 9 if("F_SJDW".equals(colum) || "F_XMPC".equals(colum) || "F_DW".equals(colum)){//字符类型 10 poiExcel.setCellStringValue(0 , index , i+1 , "null".equals(""+rs.getString(colum))?" ":rs.getString(colum) ); 11 }else if("F_YEAR".equals(colum)){//合并单元格 12 thisCell = "null".equals(""+rs.getString(colum))?" ":rs.getString(colum); 13 // poiExcel.setCellStringValue(0 , index , i+1 , thisCell); 14 }else{//数字类型 15 poiExcel.setCellDoubleValue(0 , index , i+1 , "null".equals(""+rs.getString(colum))? 0 :rs.getDouble(colum) ); 16 } 17 } 18 19 if(!thisCell.equals(lastCell)){//上一次的值和当前的值不相等 20 if(index == 3){//设置初始值 21 lastCell = thisCell; 22 lastRowIndex = index; 23 }else{ 24 poiExcel.getSheet(0).addMergedRegion(new CellRangeAddress(lastRowIndex,index-1,(short)2,(short)2)); 25 poiExcel.setCellStringValue(0 , lastRowIndex , 2 , lastCell); 26 lastCell = thisCell;//记录最后的值 27 lastRowIndex = index; 28 } 29 } 30 index++; 31 } 32 if(index>3){ 33 poiExcel.getSheet(0).addMergedRegion(new CellRangeAddress(lastRowIndex,index-1,(short)2,(short)2)); 34 System.out.println(lastRowIndex); 35 poiExcel.setCellStringValue(0 , lastRowIndex , 2 , lastCell); 36 }
说明“:
合并单元格的关键性代码为:
poiExcel.getSheet(0).addMergedRegion(new CellRangeAddress(lastRowIndex,index-1,(short)2,(short)2));
第一个参数lastRowIndex:起始行号,二个参数为终止行号,第三个参数为起始列,第四个参数为终止列,其中行的范围和列的范围皆为闭区间。
向合并单元格中写入值分为两种情况:
(1)可以先每行都写入值,然后在进行合并单元格
(2)先合并单元格,然后在合并后的第一个单元格中写入值,个人推荐使用第二种。