原理就是调用合并单元格之前把要合并的区域都设置一遍样式,当然你也可以合并之后再设置样式
public static void exportData(Sheet sheet) {
// --------设置边框、内容居中---------
Font font = sheet.getWorkbook().createFont();
DataFormat df = sheet.getWorkbook().createDataFormat();
font.setFontName("微软雅黑");
font.setFontHeightInPoints((short) 11);
CellStyle cellStyle = sheet.getWorkbook().createCellStyle();
cellStyle.setAlignment(CellStyle.ALIGN_CENTER);// 水平居中
cellStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);// 垂直居中
cellStyle.setBorderTop(CellStyle.BORDER_THIN);// 上边框
cellStyle.setBorderBottom(CellStyle.BORDER_THIN);// 下边框
cellStyle.setBorderLeft(CellStyle.BORDER_THIN);// 左边框
cellStyle.setBorderRight(CellStyle.BORDER_THIN);// 右边框
cellStyle.setFont(font);
//.................
//合并区域单元格下标
int firstRow=0;
int lastRow=2;
int firstCol=0;
int lastCol=10;
//设置合并区域单元格样式
setStyleBeforeMerging(sheet, firstRow, lastRow, firstCol, lastCol, cellStyle );
//设置单元格
CellRangeAddress region = new CellRangeAddress(firstRow, lastRow,firstCol, lastCol);
sheet.addMergedRegion(region);
//.................
}
/**
* <p>
* Description: 合并单元格之前设置单元格的样式,避免合并后部分失效
* </p>
* @param sheet excel的sheet
* @param firstRow 开始行下标
* @param lastRow 结束行下标
* @param firstCol 开始列下标
* @param lastCol 结束列下标
* @param style 样式
*/
public static void setStyleBeforeMerging(Sheet sheet, int firstRow, int lastRow, int firstCol, int lastCol, CellStyle style) {
if(lastRow>=firstRow) {
//设置合并单元格之前,先设置一遍样式
for (int l = firstRow; l <=lastRow; l++) {
Row row=CellUtil.getRow(l, sheet);
for (int k = firstCol; k <= lastCol; k++) {
Cell cell = CellUtil.getCell(row, k);
cell.setCellStyle(style);
}
}
}
}