合並單元格的方法:
指定 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();
}
}
運行結果,得到的 Excel 表如下所示:
當然也可以更復雜些的,如下圖,需要自己計算好行與列即可