zoukankan      html  css  js  c++  java
  • Java使用POI操作Excel合并单元格

    合并单元格的方法:
    指定 4 个参数,起始行,结束行,起始列,结束列。然后这个区域将被合并。

    CellRangeAddress region = new CellRangeAddress(startRow, endRow, startCol, endCol);
    sheet.addMergedRegion(region);
    

    合并的简单示例:

    public class TestExcel {
    
        public static void main(String[] args) throws IOException {
    
            HSSFWorkbook workbook = new HSSFWorkbook();
    
            HSSFCellStyle style = workbook.createCellStyle();
            style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
            style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
    
            HSSFSheet sheet = workbook.createSheet("sheet");
    
            HSSFRow row0 = sheet.createRow(0);
            HSSFCell cell_00 = row0.createCell(0);
            cell_00.setCellStyle(style);
            cell_00.setCellValue("日期");
            HSSFCell cell_01 = row0.createCell(1);
            cell_01.setCellStyle(style);
            cell_01.setCellValue("午别");
    
            HSSFRow row1 = sheet.createRow(1);
            HSSFCell cell_10 = row1.createCell(0);
            cell_10.setCellStyle(style);
            cell_10.setCellValue("20180412");
            HSSFCell cell_11 = row1.createCell(1);
            cell_11.setCellStyle(style);
            cell_11.setCellValue("上午");
    
            HSSFRow row2 = sheet.createRow(2);
            HSSFCell cell_21 = row2.createCell(1);
            cell_21.setCellStyle(style);
            cell_21.setCellValue("下午");
    
            // 合并日期占两行(4个参数,分别为起始行,结束行,起始列,结束列)
            // 行和列都是从0开始计数,且起始结束都会合并
            // 这里是合并excel中日期的两行为一行
            CellRangeAddress region = new CellRangeAddress(1, 2, 0, 0);
            sheet.addMergedRegion(region);
    
            File file = new File("E:\demo.xls");
            FileOutputStream fout = new FileOutputStream(file);
            workbook.write(fout);
            fout.close();
        }
    
    }
    ————————————————
    版权声明:本文为CSDN博主「yx0628」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
    原文链接:https://blog.csdn.net/yx0628/article/details/79914886
    

    运行结果,得到的 Excel 表如下所示:

     当然也可以更复杂些的,如下图,需要自己计算好行与列即可:

    版权声明:本文为CSDN博主「yx0628」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
    原文链接:https://blog.csdn.net/yx0628/article/details/79914886
  • 相关阅读:
    Assert.isTrue 用法
    P2967 [USACO09DEC]视频游戏的麻烦Video Game Troubles
    最近目标2333
    LibreOJ β Round #2」贪心只能过样例
    CF1062F Upgrading Cities 拓扑排序
    CF1108F MST Unification
    CF915D Almost Acyclic Graph 拓扑排序
    Swift日历控件Calendar
    README.md的markdown语法
    MAC打开App显示已损坏
  • 原文地址:https://www.cnblogs.com/wwssgg/p/15073938.html
Copyright © 2011-2022 走看看