需求很简单,在 word 表格中有一个模板行,在它下面插入 N 行数据,插入的数据行,样式和格式要和模板行一样。
通过
XmlObject copy = defRow.getCtRow().copy();
table.addRow(new XWPFTableRow((CTRow) copy), table);
这种方式,尽管可以插入新的行,可数据写不进单元格。其原因是 copy() 不是深拷贝,其内容依然依赖原行。
只能自己手工创建行,并且指定样式和原样式一样。
XWPFTableRow newRow = table.insertNewTableRow(++dataRowIndex); createCellsAndCopyStyles(newRow, defRow); private static void createCellsAndCopyStyles(XWPFTableRow targetRow, XWPFTableRow sourceRow) { targetRow.getCtRow().setTrPr(sourceRow.getCtRow().getTrPr()); List<XWPFTableCell> tableCells = sourceRow.getTableCells(); if (CollectionUtils.isEmpty(tableCells)) { return; } for (XWPFTableCell sourceCell : tableCells) { XWPFTableCell newCell = targetRow.addNewTableCell(); newCell.getCTTc().setTcPr(sourceCell.getCTTc().getTcPr()); List<XWPFParagraph> sourceParagraphs = sourceCell.getParagraphs(); if (CollectionUtils.isEmpty(sourceParagraphs)) { continue; } XWPFParagraph sourceParagraph = sourceParagraphs.get(0); List<XWPFParagraph> targetParagraphs = newCell.getParagraphs(); if (CollectionUtils.isEmpty(targetParagraphs)) { XWPFParagraph p = newCell.addParagraph(); p.getCTP().setPPr(sourceParagraph.getCTP().getPPr()); XWPFRun run = p.getRuns().isEmpty() ? p.createRun() : p.getRuns().get(0); run.setFontFamily(sourceParagraph.getRuns().get(0).getFontFamily()); } else { XWPFParagraph p = targetParagraphs.get(0); p.getCTP().setPPr(sourceParagraph.getCTP().getPPr()); XWPFRun run = p.getRuns().isEmpty() ? p.createRun() : p.getRuns().get(0); run.setFontFamily(sourceParagraph.getRuns().get(0).getFontFamily()); } } }
网上找的例子实在坑死人。