XWPFDocument 常用操作

Word 表格操作

列合并

/**
 * 列合并
 * @param table 表
 * @param col  单元格
 * @param fromRow 开始行
 * @param toRow 结束行
 */
// word跨行并单元格
public static 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);
        }
    }
}

列合行

/**
 * 列合行
 * @param table 表
 * @param row 单元格
 * @param fromCell 开始列
 * @param toCell 结束列
 */
public static 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 ) {
            cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.RESTART);
        } else {
            cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.CONTINUE);
        }
    }
}
posted @ 2021-09-07 16:16  `初一`  阅读(1355)  评论(0编辑  收藏  举报