合并单元格
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 | //判断除表头外有数据再计算单元格合并 if (sheet.getPhysicalNumberOfRows() > 1){ Integer[] mergeBasis= new Integer[]{0,1}; Integer[] mergeCells= new Integer[]{0,1}; if (mergeBasis != null && mergeBasis.length > 0 && mergeCells != null && mergeCells.length > 0){ for ( int i = 0 ; i < mergeCells.length ; i++){ mergedRegion(sheet,mergeCells[i],1,sheet.getLastRowNum(),workbook,mergeBasis); } } } private static void mergedRegion(XSSFSheet sheet, int cellLine, int startRow, int endRow, XSSFWorkbook workbook, Integer[] mergeBasis) { XSSFCellStyle style = workbook.createCellStyle(); // 样式对象 style.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER); // 垂直 style.setAlignment(XSSFCellStyle.ALIGN_CENTER); // 水平 String s_will = sheet.getRow(startRow).getCell(cellLine).getStringCellValue(); // 获取第一行的数据,以便后面进行比较 int count = 0; Set<Integer> set = new HashSet<Integer>(); CollectionUtils.addAll( set , mergeBasis); for ( int i = 2; i <= endRow; i++) { String s_current = sheet.getRow(i).getCell(cellLine).getStringCellValue(); if (s_will. equals (s_current)) { boolean isMerge = true ; if (! set .contains(cellLine)){ //如果不是作为基准列的列 需要所有基准列都相同 for ( int j = 0 ; j < mergeBasis.length ; j++){ if (!sheet.getRow(i).getCell(mergeBasis[j]).getStringCellValue() . equals (sheet.getRow(i-1).getCell(mergeBasis[j]).getStringCellValue())){ isMerge = false ; } } } else { //如果作为基准列的列 只需要比较列号比本列号小的列相同 for ( int j = 0 ; j < mergeBasis.length && mergeBasis[j] < cellLine ; j++){ if (!sheet.getRow(i).getCell(mergeBasis[j]).getStringCellValue() . equals (sheet.getRow(i-1).getCell(mergeBasis[j]).getStringCellValue())){ isMerge = false ; } } } if (isMerge){ count++; } else { sheet.addMergedRegion( new CellRangeAddress( startRow, startRow+count,cellLine , cellLine)); startRow = i; s_will = s_current; count = 0; } } else { sheet.addMergedRegion( new CellRangeAddress( startRow, startRow+count,cellLine , cellLine)); startRow = i; s_will = s_current; count = 0; } if (i == endRow && count > 0) { sheet.addMergedRegion( new CellRangeAddress(startRow,startRow+count ,cellLine , cellLine)); } } } |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步