How to merge cells horizontally using apache-poi

余生颓废 提交于 2019-12-11 12:24:12

问题


I get to do a vertically merged using this function:

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

but I can't do the horizontal merge with similar function:

private static void mergeCellsHorizontally(XWPFTable table, int col, int fromCol, int toCol) {

    for (int colIndex = fromCol; colIndex <= toCol; colIndex++) {

        XWPFTableCell cell = table.getRow(0).getCell(colIndex);

        if ( colIndex == fromCol ) {
            // The first merged cell is set with RESTART merge value
            cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.RESTART);
            cell.setText("hola");
        } else {
            // Cells which join (merge) the first one, are set with CONTINUE
            cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.CONTINUE);
            cell.setText("adios");
        }
    }
}

Thanks!


回答1:


The solution is:

  setCellSpan(row.getCell(2), 5);
   CTRow ctRow = row.getCtRow(); 
    CTTc[] ctTcs = new CTTc[4]; // las colunas que quedan
    for(int y = 0; y < ctRow.sizeOfTcArray(); y++) { 
       if(y != 4 && y != 5  && y != 6 && y != 7){ //Las columnas que desaparecen
    ctTcs[y] = ctRow.getTcArray(y);
} }ctRow.setTcArray(ctTcs);  

where:

public static void setCellSpan(XWPFTableCell cell, int span) {
    if (cell.getCTTc().getTcPr() == null) {
        cell.getCTTc().addNewTcPr();
    }
    if (cell.getCTTc().getTcPr().getGridSpan() == null) {
        cell.getCTTc().getTcPr().addNewGridSpan();
    }
    cell.getCTTc().getTcPr().getGridSpan().setVal(BigInteger.valueOf((long) span));
}


来源:https://stackoverflow.com/questions/35554185/how-to-merge-cells-horizontally-using-apache-poi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!