使用POI创建word表格合并单元格兼容wps
poi创建word表格合并单元格代码如下:
跨列合并:
/**
* @Description: 跨列合并
*/
public void mergeCellsHorizontal(XWPFTable table, int row, int fromCell, int toCell) {
for (int cellIndex = fromCell; cellIndex <= toCell; cellIndex++) {
XWPFTableCell cell = table.getRow(row).getCell(cellIndex);
if ( cellIndex == fromCell ) {
// The first merged cell is set with RESTART merge value
cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.RESTART);
} else {
// Cells which join (merge) the first one, are set with CONTINUE
cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.CONTINUE);
}
}
}
跨行合并:
/**
* @Description: 跨行合并
* @see http://stackoverflow.com/questions/24907541/row-span-with-xwpftable
*/
public void mergeCellsVertically(XWPFTable table, int col, int fromRow, int toRow) {
for (int rowIndex = fromRow; rowIndex <= toRow; rowIndex++) {
XWPFTableCell cell = table.getRow(rowIndex).getCell(col);
if ( rowIndex == fromRow ) {
// The first merged cell is set with RESTART merge value
cell.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.RESTART);
} else {
// Cells which join (merge) the first one, are set with CONTINUE
cell.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.CONTINUE);
}
}
}
但是以上方法在wps中不兼容,wps跨列合并单元格后会出现一些问题。如图所示:

而在office中的正确结果(我想要的)如下所示:

这是由于我设置了表格列宽自动分割:
// 列宽自动分割 CTTblWidth width = table.getCTTbl().addNewTblPr().addNewTblW(); width.setType(STTblWidth.DXA); width.setW(BigInteger.valueOf(9072));
导致在wps中第一行虽然合并了“纸媒”、“新媒体”单元格,但由于设置了列宽自动分割,致使在wps中单元格竖线没有对齐,而是均匀的分成了三个列宽相同的单元格。
解决办法如下:设置合并的单元格的宽度(“纸媒”、“新媒体”单元格),则在wps中竖线就对上了。
//设置合并单元格的大小
//rowNum:合并的单元格所在行号 fromCellNum:合并的起始单元格 toCellNum:合并的结束单元格 9072:列宽总大小(我写死了9072) columnNum:表格总列数
table.getRow(rowNum).getCell(fromCellNum).getCTTc().addNewTcPr().addNewTcW()
.setW(BigInteger.valueOf((9072 / columnNum) * (toCellNum - fromCellNum + 1)));
实际项目开发中使用如下:
/**
* 跨列合并表格是4列,所以8600/4,项目中需要在最后一行合并2、3、4列,所以fromCell=1,toCell=3
* @param table
* @param row 所合并的行
* @param fromCell 起始列
* @param toCell 终止列
*/
public void mergeCellsHorizontal(XWPFTable table, int row, int fromCell, int toCell) {
table.getRow(row).getCell(fromCell).getCTTc().addNewTcPr().addNewTcW()
.setW(BigInteger.valueOf((8600 / 4) * (toCell - fromCell + 1)));
for (int cellIndex = fromCell; cellIndex <= toCell; cellIndex++) {
XWPFTableCell cell = table.getRow(row).getCell(cellIndex);
if ( cellIndex == fromCell ) {
// The first merged cell is set with RESTART merge value
cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.RESTART);
} else {
// Cells which join (merge) the first one, are set with CONTINUE
cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.CONTINUE);
}
}
}

浙公网安备 33010602011771号