java 合并excel单元格

直接上代码

public static HSSFWorkbook getHSSFWorkbookTitle(String startTime,String sheetName,String [][]values, HSSFWorkbook workbook) throws IOException {
        // 第一步,创建一个HSSFWorkbook,对应一个Excel文件
        if(workbook == null){
            workbook = new HSSFWorkbook();
        }
        HSSFCellStyle style = workbook.createCellStyle();
        style.setAlignment(CENTER);
//        style.setVerticalAlignment(VERTICAL_CENTER);
        HSSFSheet sheet = workbook.createSheet("sheet");
        CellRangeAddress region = new CellRangeAddress(0, 1, 0, 11);
        sheet.addMergedRegion(region);
        CellRangeAddress region2 = new CellRangeAddress(0, 1, 12, 12);
        sheet.addMergedRegion(region2);
        HSSFRow row0 = sheet.createRow(0);
        HSSFCell cell_00 = row0.createCell(0);
        HSSFCell cell_01 = row0.createCell(12);
        cell_00.setCellStyle(style);
        cell_00.setCellValue(sheetName);
        cell_01.setCellStyle(style);
        cell_01.setCellValue(startTime);
        // 合并日期占两行(4个参数,分别为起始行,结束行,起始列,结束列)
        // 行和列都是从0开始计数,且起始结束都会合并
        // 这里是合并excel中日期的两行为一行
        CellRangeAddress region3 = new CellRangeAddress(2, 3, 0, 0);
        sheet.addMergedRegion(region3);
        CellRangeAddress region4 = new CellRangeAddress(2, 3, 1, 1);
        sheet.addMergedRegion(region4);
        CellRangeAddress region6 = new CellRangeAddress(2, 3, 2, 2);
        sheet.addMergedRegion(region6);
        HSSFRow row2 = sheet.createRow(2);
        HSSFCell cell_20 = row2.createCell(0);
        cell_20.setCellStyle(style);
        cell_20.setCellValue("标题一");
        HSSFCell cell_21 = row2.createCell(1);
        cell_21.setCellStyle(style);
        cell_21.setCellValue("标题二");
        HSSFCell cell_22 = row2.createCell(2);
        cell_22.setCellStyle(style);
        cell_22.setCellValue("标题三");
  
        //创建内容
        for(int i=0;i<values.length;i++){
            row0 = sheet.createRow(i + 4);
            for(int j=0;j<values[i].length;j++){
                //将内容按顺序赋给对应的列对象
                row0.createCell(j).setCellValue(values[i][j]);
            }
        }

        return workbook;
    }

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