Java使用POI导出Excel时合并单元格

在填充好sheet内容之后:

//判断除表头外有数据再计算单元格合并
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);
        }
    }
}

其中mergeBasis 合并基准列,mergeCells 要合并的列。

下面为合并单元格方法

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 set = new HashSet();
    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));
        }
    }
}

 

 

你可能感兴趣的:(Java)