poi - word合并单元格,拖动之后还原问题

word 文件合并单元格,在网络上,很容易找到下面这个函数,
但是,这个函数有一个 bug,如果拖动单元格,合并的单元格又会重新还原。

class Test {
    /**
     * word单元格列合并
     *
     * @param table     表格
     * @param row       合并列所在行
     * @param startCell 开始列
     * @param endCell   结束列
     */
    public static void mergeCellsHorizontal(XWPFTable table, int row, int startCell, int endCell) {
        for (int i = startCell; i <= endCell; i++) {
            XWPFTableCell cell = table.getRow(row).getCell(i);
            if (i == startCell) {
                // 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);
            }
        }
    }
}

其实 office 相关的文件,如果想知道文档结构,可以用一种很简单的方式:将文件另存为 xml 格式;

下面是 word 文档转换成 xml 之后,单元格相关的代码。

对于上面的代码 cell.getCTTc().addNewTcPr(),你可能一开始不能理解,但是看过 xml 格式,大致就能猜出来了。

    <w:tc>
        <w:tcPr>
            <w:tcW w:w="0" w:type="auto"/>
        </w:tcPr>
        <w:p w14:paraId="3049E24E" w14:textId="77777777" w:rsidR="00B21DED" w:rsidRDefault="00ED7147">
            <w:pPr>
                <w:jc w:val="center"/>
            </w:pPr>
            <w:r>
                <w:t>杭州市</w:t>
            </w:r>
        </w:p>
    </w:tc>

回归到上面这个问题,为什么拖拽之后就还原了呢?

因为合并之后,并未删除单元格,w:r 标签仍然存在,代码再加一两行,清除多余的 w:r 标签即可。

class Test{
    /**
     * word单元格列合并
     *
     * @param table     表格
     * @param row       合并列所在行
     * @param startCell 开始列
     * @param endCell   结束列
     */
    public static void mergeCellsHorizontal(XWPFTable table, int row, int startCell, int endCell) {
        for (int i = startCell; i <= endCell; i++) {
            XWPFTableCell cell = table.getRow(row).getCell(i);
            if (i == startCell) {
                // 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);
                // 关键是这一行,要 removeR() 多少次,取决于你文档中实际数量
                cell.getCTTc().getPArray(0).removeR(0);
            }
        }
    }
}

posted on 2020-10-31 17:52  疯狂的妞妞  阅读(640)  评论(0编辑  收藏  举报

导航