如何使用apache-poi水平合并单元格 [英] How to merge cells horizontally using apache-poi
本文介绍了如何使用apache-poi水平合并单元格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我可以使用以下功能进行垂直合并:
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");
}
}
}
谢谢!
推荐答案
解决方案是:
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));
}
这篇关于如何使用apache-poi水平合并单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文