在poi中创建一个表非常简单,但它的教程非常有限,我找不到一个可以在生成docx文件的表中创建一个简单的合并单元格。
答案 0 :(得分:7)
如果您已创建表,行内的行和行内的单元格,则可以将gridSpan添加到单元格属性中:
if (cell.getCTTc().getTcPr() == null) cell.getCTTc().addNewTcPr();
if (cell.getCTTc().getTcPr().getGridSpan() == null) cell.getCTTc().getTcPr().addNewGridSpan();
cell.getCTTc().getTcPr().getGridSpan().setVal(2);
注意:cell是org.apache.poi.xwpf.usermodel.XWPFTableCell。
答案 1 :(得分:5)
为每个表行创建单独的XWPFTable
将起作用,应该完全没问题。所有表在后台合并到最终word文档中的一个表。您将需要所有这些广告,poi-3.9.jar
,poi-ooxml-3.9.jar
和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));
}
答案 2 :(得分:3)
要水平/垂直合并,您需要创建2个CTHMerge并使用setVal:
a)2x2表(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)垂直合并(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);