//获取要添加合并单元格的sheet对象,或者直接创建也是可以的
Sheet sheet = wb.getSheetAt(0);
//创建一个cell的样式
CellStyle cellStyle = wb.createCellStyle();
// 设置自动换行
cellStyle.setWrapText(true);
//创建行(index是从0开始算),这里是直接创建第2行
Row row_2=sheet.createRow(1);
//给第2行创建第1列(index是从0开始算)
Cell cell_1 = row_2.createCell(0);
//给第2行第1列赋值(\r\n 换行)
cell_1.setCellValue("测试:\r\n20211210" );
//注意:加了换行标识要设置样式为自动换行
cell_1.setCellStyle(cellStyle);
//给第2行创建第2列并设置值
Cell cell_2 = row_2.createCell(1);
cell_2.setCellValue("2021" );
//给第2行创建第4列并设置值
Cell cell_4 = row_2.createCell(3);
cell_4 .setCellValue("12" );
//给第2行创建第5列并设置值
Cell cell_5 = row_2.createCell(4);
cell_5 .setCellValue("12" );
//给第2行创建第6列并设置值
Cell cell_6 = row_2.createCell(5);
cell_6 .setCellValue("10" );
//创建第3行并创建对应列并赋值
Row row_3=sheet.createRow(2);
Cell cell_1 = row_3.createCell(0);
cell_1.setCellValue("测试:\r\n2021121011" );
Cell cell_2 = row_3.createCell(1);
cell_2.setCellValue("2021" );
Cell cell_4 = row_3.createCell(3);
cell_4 .setCellValue("12" );
Cell cell_5 = row_3.createCell(4);
cell_5 .setCellValue("12" );
Cell cell_6 = row_3.createCell(5);
cell_6 .setCellValue("11" );
//合并单元格(4个参数,分别为起始行,结束行,起始列,结束列)
sheet.addMergedRegion(new CellRangeAddress(1, 2, 1, 1));
//合并单元格:注意不能单个单元格执行这个合并,不然会报错。如:new CellRangeAddress(1,1,2,2)
sheet.addMergedRegion(new CellRangeAddress(1, 2, 3, 4));
生成的excel效果图为: