我可以使用此函数进行垂直合并:
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");
}
}
}
谢谢!
最佳答案
解决方案是:
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));
}
关于java - 如何使用 apache-poi 水平合并单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35554185/