POI实现合并后居中

  我看网上有很多关于POI合并后居中的实现,但是都不能满足效果,自己封装了一个工具类。基本能cover日常的开发需求。

工具类在下方自取


如果要实现合并后居中,只要如下几行代码,就可以轻松实现。

 String[] styleGenerator = new String[]{"float:center", "font-size:11", "font-style:宋体", "bold"};
 XSSFCellStyle titleStyle = PoiUtils.styleFactory(sheet,styleGenerator);
 PoiUtils.setCellValueWithStyle(sheet,0,2,"期初数",titleStyle);
 PoiUtils.mergeCells(sheet,0,0,2,6);

效果如下所示

POI实现合并后居中_第1张图片

public class PoiUtils {
    /**
     * @param cell  当前cell
     * @param sheet 当前sheet
     * @Description: 获取当前cell合并的行数
     */
    public static int getMergeRowNum(Cell cell, Sheet sheet) {
        int mergeSize = 1;
        List<CellRangeAddress> mergedRegions = sheet.getMergedRegions();
        for (CellRangeAddress cellRangeAddress : mergedRegions) {
            if (cellRangeAddress.isInRange(cell)) {
                //获取合并的行数
                mergeSize = cellRangeAddress.getLastRow() - cellRangeAddress.getFirstRow() + 1;
                break;
            }
        }
        return mergeSize;
    }

    /**
     * @param cell  当前cell
     * @param sheet 当前sheet
     * @Description: 获取合并的列数
     */
    public static int getMergeColumNum(Cell cell, Sheet sheet) {
        int mergeSize = 1;
        List<CellRangeAddress> mergedRegions = sheet.getMergedRegions();
        for (CellRangeAddress cellRangeAddress : mergedRegions) {
            if (cellRangeAddress.isInRange(cell)) {
                //获取合并的列数
                mergeSize = cellRangeAddress.getLastColumn() - cellRangeAddress.getFirstColumn() + 1;
                break;
            }
        }
        return mergeSize;
    }

    public static List<String> getColumnStringList(Row row , int cellnum , int length){
        List<String> stringList = new ArrayList<>();
        IntStream.range(0 , length).forEach(index -> {
            String stringValue = row.getCell(cellnum + index).getStringCellValue();
            if(!StringUtils.isEmpty(stringValue)){
                stringList.add(stringValue);
            }
        });
        return stringList;
    }

    public static List<String> getRowStringList(Sheet sheet,int columnNum , int rowNum , int length){
        List<String> stringList = new ArrayList<>();
        IntStream.range(0 , length).forEach(index -> {
            if(null != sheet.getRow(rowNum+index) && null != sheet.getRow(rowNum+index).getCell(columnNum)){
                String stringValue = sheet.getRow(rowNum+index).getCell(columnNum).getStringCellValue();
                if(!StringUtils.isEmpty(stringValue)){
                    stringList.add(stringValue);
                }
            }
        });
        return stringList;
    }

    public static List<String> getNumericColumnStringList(Row row , int cellnum , int length){
        List<String> stringList = new ArrayList<>();
        IntStream.range(0 , length).forEach(index -> {
            Cell temp = row.getCell(cellnum+index);
            temp.getCellType();
            String stringValue = row.getCell(cellnum + index).getStringCellValue().split("\\.")[0];
            if(!StringUtils.isEmpty(stringValue)){
                stringList.add(stringValue);
            }
        });
        return stringList;
    }


    public static void setCellValue(Sheet sheet , int rownum , int cellnum , Object value){
        Row row = null != sheet.getRow(rownum) ? sheet.getRow(rownum) : sheet.createRow(rownum);
        Cell cell = null != row.getCell(cellnum) ? row.getCell(cellnum) : row.createCell(cellnum);
        if(value instanceof String){
            cell.setCellValue((String) value);
        }
        if(value instanceof Double){
            cell.setCellValue((Double) value);
        }
    }


    public static void setCellFormula(Sheet sheet , int rownum , int cellnum , String formula){
        Row row = null != sheet.getRow(rownum) ? sheet.getRow(rownum) : sheet.createRow(rownum);
        Cell cell = null != row.getCell(cellnum) ? row.getCell(cellnum) : row.createCell(cellnum);
        cell.setCellFormula(formula);
    }

    public static void mergeCells(Sheet sheet , int firstRow , int lastRow , int firstCol , int lastCol){
        if(lastRow - firstRow == 0 && lastCol - firstCol == 0){//没有需要合并的单元格
            return;
        }
        CellRangeAddress region = new CellRangeAddress(firstRow, lastRow, firstCol, lastCol);
        sheet.addMergedRegion(region);
    }

    /*设置单元格样式*/
    public static void setCellStyle(Sheet sheet,int rownum,int cellnum,String[] style){
        Cell cell = getCell(sheet,rownum,cellnum);
        CellStyle cellStyle = styleFactory(sheet,style);
        cell.setCellStyle(cellStyle);
    }

    /*设置单元格样式*/
    public static void setCellStyle(Sheet sheet,int rownum,int cellnum,XSSFCellStyle style){
        Cell cell = getCell(sheet,rownum,cellnum);
        cell.setCellStyle(style);
    }

    /*带样式设置单元格*/
    public static void setCellValueWithStyle(Sheet sheet,int rownum,int cellnum,Object value,String[] style){
        Row row = null != sheet.getRow(rownum) ? sheet.getRow(rownum) : sheet.createRow(rownum);
        Cell cell = null != row.getCell(cellnum) ? row.getCell(cellnum) : row.createCell(cellnum);
        XSSFCellStyle cellStyle = styleFactory(sheet,style);
        cell.setCellStyle(cellStyle);
        if(value instanceof String){
            cell.setCellValue((String) value);
        }
        if(value instanceof Double){
            cell.setCellValue((Double) value);
        }
    }

    /*带样式设置单元格*/
    public static void setCellValueWithStyle(Sheet sheet,int rownum,int cellnum,Object value,XSSFCellStyle style){
        Row row = null != sheet.getRow(rownum) ? sheet.getRow(rownum) : sheet.createRow(rownum);
        Cell cell = null != row.getCell(cellnum) ? row.getCell(cellnum) : row.createCell(cellnum);
        cell.setCellStyle(style);
        if(value instanceof String){
            cell.setCellValue((String) value);
        }
        if(value instanceof Double){
            cell.setCellValue((Double) value);
        }
    }


    /*获取某个单元格*/
    public static Cell getCell(Sheet sheet,int rownum,int cellnum){
        Row row = null != sheet.getRow(rownum) ? sheet.getRow(rownum) : sheet.createRow(rownum);
        Cell cell = null != row.getCell(cellnum) ? row.getCell(cellnum) : row.createCell(cellnum);
        return cell;
    }

    /*获取某个单元格的值*/
    public static Object getCellValue(Cell cell) throws Exception {
        switch (cell.getCellTypeEnum()){
            case STRING:
                return cell.getStringCellValue();
            case NUMERIC:
                return cell.getNumericCellValue();
            case FORMULA:
                return cell.getCellFormula();
            default:
                throw new Exception("目前只接受 String/number/formula");
        }
    }

    /*合并区域最外边框*/
    public static void setMergedCellStyle(Sheet sheet , int firstRow , int lastRow , int firstCol , int lastCol){
        if(firstRow>=lastRow){
            System.out.print("首行不能大于末行");
            return;
        }else{
            CellRangeAddress cra = new CellRangeAddress(firstRow,lastRow,firstCol,lastCol);
            BorderStyle border = org.apache.poi.ss.usermodel.BorderStyle.THIN;
            RegionUtil.setBorderBottom(border,cra,sheet);                                                                   //全边框
            RegionUtil.setBorderTop(border,cra,sheet);
            RegionUtil.setBorderLeft(border,cra,sheet);
            RegionUtil.setBorderRight(border,cra,sheet);

            Cell cell = getCell(sheet,firstRow,firstCol);
            CellUtil.setVerticalAlignment(cell, VerticalAlignment.CENTER);                                                  //文字垂直居中
        }
    }

    /*区域每个单元格边框*/
    public static void setRegionCellStyle(Sheet sheet , int firstRow , int lastRow , int firstCol , int lastCol,String[] style){
        for(int i=firstRow;i<lastRow;i++) {
            for(int j=firstCol ; j<lastCol;j++){
                PoiUtils.setCellStyle(sheet,i,j,style);
            }
        }
    }

    /*设置全局单元格边框,包括合并单元格*/
    public static void setGlobalBorder(Sheet sheet, int firstRow , int lastRow , int firstCol , int lastCol,String position) throws Exception {
        BorderStyle border = org.apache.poi.ss.usermodel.BorderStyle.THIN;
        try{
            for (int i = firstRow; i <= lastRow; i++) {
                for (int j = firstCol;j<= lastCol;j++){
                    Cell cell = getCell(sheet,i,j);

                    if(position.equals("left")){
                        CellUtil.setCellStyleProperty(cell, CellUtil.BORDER_LEFT, border);
                    }
                    if(position.equals("right")){
                        CellUtil.setCellStyleProperty(cell, CellUtil.BORDER_RIGHT, border);
                    }
                    if(position.equals("top")){
                        CellUtil.setCellStyleProperty(cell, CellUtil.BORDER_TOP, border);
                    }
                    if(position.equals("bottom")){
                        CellUtil.setCellStyleProperty(cell, CellUtil.BORDER_BOTTOM, border);
                    }
                    if(position.equals("all")){
                        CellUtil.setCellStyleProperty(cell, CellUtil.BORDER_LEFT, border);
                        CellUtil.setCellStyleProperty(cell, CellUtil.BORDER_RIGHT, border);
                        CellUtil.setCellStyleProperty(cell, CellUtil.BORDER_TOP, border);
                        CellUtil.setCellStyleProperty(cell, CellUtil.BORDER_BOTTOM, border);
                    }else {
                        System.out.print("位置信息不合法,接受position为left/right/top/bottom/all");
                    }
                }
            }
        }
        catch (Exception e){
            throw new Exception("位置信息不合法,接受position为left/right/top/bottom/all");
        }



    }

    /*设置列宽*/
    public static void setColumnWidth(Sheet sheet,int cellnum,int width_px){                                                         //设置某列宽度
        sheet.setColumnWidth(cellnum,width_px*255);
    }

    /*判空行*/
    public static boolean isBlankRow(XSSFRow row){                                                                      //判断行为空
        if(row == null) return true;
        boolean result = true;
        for(int i = row.getFirstCellNum(); i < row.getLastCellNum(); i++){
            XSSFCell cell = row.getCell(i);
            String value = "";
            if(cell != null){
                switch (cell.getCellType()) {
                    case Cell.CELL_TYPE_STRING:
                        value = cell.getStringCellValue();
                        break;
                    case Cell.CELL_TYPE_NUMERIC:
                        value = String.valueOf((int) cell.getNumericCellValue());
                        break;
                    case Cell.CELL_TYPE_BOOLEAN:
                        value = String.valueOf(cell.getBooleanCellValue());
                        break;
                    case Cell.CELL_TYPE_FORMULA:
                        value = String.valueOf(cell.getCellFormula());
                        break;
                    //case Cell.CELL_TYPE_BLANK:
                    //	break;
                    default:
                        break;
                }
                if(!value.trim().equals("")){
                    result = false;
                    break;
                }
            }
        }
        return result;
    }                                                                  //判断行为空

    /*初始化  设置单元格边框+百分比*/
    public static void setCellWithBorder(Sheet sheet,int row,int col){
        XSSFWorkbook workbook = (XSSFWorkbook) sheet.getWorkbook();
        XSSFCellStyle style = workbook.createCellStyle();

        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        style.setBorderTop(BorderStyle.THIN);

        /*设置百分比格式*/
        style.setDataFormat(
                workbook.createDataFormat().getFormat("##.00%")
        );

        Cell cell = getCell(sheet,row,col);
        cell.setCellStyle(style);
        cell.setCellValue(0.00);
    }

    /*样式工厂*/
    public static XSSFCellStyle styleFactory(Sheet sheet,String args[]){
        Workbook workbook = sheet.getWorkbook();
        XSSFCellStyle style = (XSSFCellStyle) workbook.createCellStyle();
        Font font=workbook.createFont();
        for (int i =0;i<args.length;i++){
            if (args[i].startsWith("percentage")){
                style.setDataFormat(
                        workbook.createDataFormat().getFormat("0.00%")
                );
            }
            if (args[i].startsWith("font-size")){
                font.setFontHeightInPoints(Short.parseShort((args[i].split(":")[1])));
            }
            if(args[i].startsWith("border")){
                style.setBorderBottom(BorderStyle.THIN);
                style.setBorderLeft(BorderStyle.THIN);
                style.setBorderRight(BorderStyle.THIN);
                style.setBorderTop(BorderStyle.THIN);
            }
            if(args[i].equals("bold")){
                font.setBold(true);
            }
            if(args[i].startsWith("font-style")){
                String fontName=args[i].split(":")[1];
                font.setFontName(fontName);
            }
            if(args[i].startsWith("float")){
                String position = args[i].split(":")[1];
                switch (position){
                    case "left":                                                                                         //靠左
                        style.setAlignment(HorizontalAlignment.LEFT);
                        break;
                    case "right":
                        style.setAlignment(HorizontalAlignment.RIGHT);                                                   //靠右
                        break;
                    case "center":
                        style.setAlignment(HorizontalAlignment.CENTER);                                                 //水平居中
                        style.setVerticalAlignment(VerticalAlignment.CENTER);                                           //垂直居中
                        break;
                    case "vertical-center":
                        style.setVerticalAlignment(VerticalAlignment.CENTER);                                           //垂直居中
                        break;
                    case "horizon-center":
                        style.setAlignment(HorizontalAlignment.CENTER);                                                 //水平居中
                        break;
                    default:
                        style.setAlignment(HorizontalAlignment.GENERAL);
                        style.setVerticalAlignment(VerticalAlignment.CENTER);
                }
            }
            if(args[i].startsWith("background-color")){
                String color = args[i].split(":")[1];
                short a;
                switch (color){
                    case"red":
                        a = IndexedColors.RED.getIndex();
                        break;
                    case"yellow":
                        a = IndexedColors.YELLOW.getIndex();
                        break;
                    case"black":
                        a = IndexedColors.BLACK.getIndex();
                        break;
                    default:
                        throw new IllegalStateException("Unexpected value: " + color);
                }
                style.setFillForegroundColor(a);
                style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
            }
        }
        style.setFont(font);
        return style;
    }


    private void setCellValue(Cell cell,Object value){
        if(value instanceof String){
            cell.setCellValue((String) value);
        }
        if(value instanceof Double){
            cell.setCellValue((Double) value);
        }
        if (value instanceof Boolean){
            cell.setCellValue((Boolean) value);
        }
    }
}

你可能感兴趣的:(java,poi,excel,java)