300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > 使用POI创建word表格合并单元格兼容wps

使用POI创建word表格合并单元格兼容wps

时间:2020-10-26 06:35:54

相关推荐

使用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 /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)));

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。