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); } } }