poi word操作之XWPFTable合并单元格
需要注意,要合并的单元格最好不要有其他的合并样式。
跨列合并单元格
/**
* @Description: 跨列合并
* table要合并单元格的表格
* row要合并哪一行的单元格
* fromCell开始合并的单元格
* toCell合并到哪一个单元格
*/
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: 跨行合并
* table要合并单元格的表格
* col要合并哪一列的单元格
* fromRow从哪一行开始合并单元格
* toRow合并到哪一个行
*/
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);
}
}
}
备注:合并office可以,wps可能不行。
拓展