zoukankan      html  css  js  c++  java
  • 使用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 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)));
  • 相关阅读:
    Spring 学习笔记
    Java Web整合开发(33) -- SSH和SSJ
    2、常用操作
    jsonp使用
    PHP curl 封装 GET及POST方法很不错的
    浅谈CSRF攻击方式 转
    谷歌插件请求ci 解决CI框架的Disallowed Key Characters错误提示
    phpstorm10.0.3 下载与激活
    Mysql全文搜索match against的用法
    CentOS 6.4下编译安装MySQL 5.6.14 (转)
  • 原文地址:https://www.cnblogs.com/henuyuxiang/p/15007286.html
Copyright © 2011-2022 走看看