1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
| public class TableMergeTest { public static void main(String[] args) throws Exception { WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.createPackage(); MainDocumentPart mainDocumentPart = wordMLPackage.getMainDocumentPart();
Tbl table = createTable(); TableTest.setTablePr(table); mainDocumentPart.addObject(table);
mergeTableCells(table, 0, 0, 1);
wordMLPackage.save(new File("D:/Desktop/TempFile/newReport/表格文档/" + DateUtil.format(new DateTime(), "yyyyMMdd-HH-mm-ss") + ".docx")); }
private static Tbl createTable() { ObjectFactory factory = new ObjectFactory(); Tbl table = factory.createTbl();
Tr row1 = factory.createTr(); addTableCell(row1, "Cell 1"); addTableCell(row1, "Cell 2"); table.getContent().add(row1);
Tr row2 = factory.createTr(); addTableCell(row2, "Cell 3"); addTableCell(row2, "Cell 4"); table.getContent().add(row2);
return table; }
private static void addTableCell(Tr row, String content) { ObjectFactory factory = new ObjectFactory(); Tc cell = factory.createTc(); P paragraph = factory.createP(); Text text = factory.createText(); text.setValue(content); R r = factory.createR(); r.getContent().add(text); paragraph.getContent().add(r); cell.getContent().add(paragraph); row.getContent().add(cell); }
private static void mergeTableCells(Tbl table, int rowIndex, int cellStartIndex, int cellEndIndex) { List<Object> rows = table.getContent(); if (rowIndex < rows.size()) { Tr row = (Tr) rows.get(rowIndex); List<Object> cells = row.getContent();
for (int i = cellStartIndex + 1; i <= cellEndIndex; i++) { TcPr tcPr = getOrCreateTcPr((Tc) cells.get(cellStartIndex)); TcPrInner.GridSpan gridSpan = new TcPrInner.GridSpan(); gridSpan.setVal(BigInteger.valueOf(cellEndIndex - cellStartIndex + 1)); tcPr.setGridSpan(gridSpan); cells.remove(cellStartIndex + 1); } } }
private static TcPr getOrCreateTcPr(Tc cell) { TcPr tcPr = cell.getTcPr(); if (tcPr == null) { tcPr = new TcPr(); cell.setTcPr(tcPr); } return tcPr; } }
|