How to merge cells (or apply colspan) using XWPFTable in POI in Java?

帅比萌擦擦* 提交于 2019-12-05 06:04:25

If you have created table, row inside a table and cell inside a row, you can add gridSpan to cell properties:

if (cell.getCTTc().getTcPr() == null) cell.getCTTc().addNewTcPr();
if (cell.getCTTc().getTcPr().getGridSpan() == null) cell.getCTTc().getTcPr().addNewGridSpan();
cell.getCTTc().getTcPr().getGridSpan().setVal(2);

Note: cell is org.apache.poi.xwpf.usermodel.XWPFTableCell.

Creating a separate XWPFTable for each table row will work and should be perfectly fine. All the tables are merged behind the scenes to one table in the final word document. You will need all of these jars, poi-3.9.jar, poi-ooxml-3.9.jar and poi-ooxml-schemas-3.9.jar

XWPFTable table1 = document.createTable(1,1); // This is your row 1
XWPFTable table2 = document.createTable(1,3); // This is your row 2

// Now it's time to span each column of table1 and table2 to a span of your choice
// lets say 6 is the total span required assuming there's some row with 6 columns.

spanCellsAcrossRow(table1, 0, 0, 6);
spanCellsAcrossRow(table2, 0, 0, 2);
spanCellsAcrossRow(table2, 0, 1, 2);
spanCellsAcrossRow(table2, 0, 2, 2);

private void spanCellsAcrossRow(XWPFTable table, int rowNum, int colNum, int span) {
    XWPFTableCell  cell = table.getRow(rowNum).getCell(colNum);
    cell.getCTTc().getTcPr().addNewGridSpan();
    cell.getCTTc().getTcPr().getGridSpan().setVal(BigInteger.valueOf((long)span));
}

To merge horizontally/vertically you need to create 2 CTHMerge and use the setVal:

  • one for the cells that you will remain (STMerge.RESTART);
  • a second one for the merged cells (STMerge.CONTINUE);

a) example for a horizontal merge for 2x2 table (image with example):

|___________|___________| --> |___________ ___________|
|___________|___________| --> |___________ ___________|

 // First Row
CTHMerge hMerge = CTHMerge.Factory.newInstance();
vmerge.setVal(STMerge.RESTART);
table.getRow(0).getCell(0).getCTTc().getTcPr().setHMerge(hMerge);
table.getRow(1).getCell(0).getCTTc().getTcPr().setHMerge(hMerge);

 // Secound Row cell will be merged/"deleted"
CTHMerge hMerge1 = CTHMerge.Factory.newInstance();
hMerge.setVal(STMerge.CONTINUE);
table.getRow(0).getCell(1).getCTTc().getTcPr().setHMerge(hMerge1);
table.getRow(1).getCell(1).getCTTc().getTcPr().setHMerge(hMerge1);

b) example of a vertical merge (image with example)

 // First Row
CTVMerge vmerge = CTVMerge.Factory.newInstance();
vmerge.setVal(STMerge.RESTART);
table.getRow(0).getCell(0).getCTTc().getTcPr().setVMerge(vmerge);
table.getRow(0).getCell(1).getCTTc().getTcPr().setVMerge(vmerge);

 // Secound Row cell will be merged 
CTVMerge vmerge1 = CTVMerge.Factory.newInstance();
vmerge.setVal(STMerge.CONTINUE);
table.getRow(1).getCell(0).getCTTc().getTcPr().setVMerge(vmerge1);
table.getRow(1).getCell(1).getCTTc().getTcPr().setVMerge(vmerge1);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!