如何使用apache-poi水平合并单元格

时间:2016-02-22 12:50:27

标签: java apache-poi xwpf

我可以使用此函数进行垂直合并:

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

但我不能用类似功能进行水平合并:

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

谢谢!

1 个答案:

答案 0 :(得分:1)

解决方案是:

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

其中:

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