我是Apache POI的初学者,想在Word模板文件中扩展现有表,并添加一些行。如果我在下面使用该代码,则将使用新的行单元格创建的普通样式扩展行位。
我的目标是单元格具有相同的表格单元格样式等(字体,带有,高度…)
XWPFDocument doc = new XWPFDocument(openFile(fileName)); XWPFTable tbl = doc.getTableArray(tableIndex); XWPFTableRow lastRow = tbl.getRows().get(tbl.getNumberOfRows() - 1); cellCounter = lastRow.getTableICells().size(); XWPFTableRow newRow = tbl.createRow(); for (int i = 0; i < data.size() && cellCounter <= data.size(); i++) { String text = data.get(i); XWPFTableCell cell = newRow.getCell(i); if (cell != null) { cell.setText(text); } }
感谢您的回答。R.
以下代码获取文档中第一个表中第二行的精确副本。然后,它更改此行中单元格的文本内容。然后将此复制的行插入到此表的第2行和第3行之间。
不断变化的内容之前必须完成table.addRow,因为该行必须在插入之前完整列表tableRows并将其添加到TrArray了的CTTbl ctTbl。以后的更改将不会写入XML。我还不知道为什么会这样。
table.addRow
TrArray
XML
然后,代码获取最后一行的副本,并将此副本添加到表的末尾。在此还必须先更改内容table.addRow。
import java.io.*; import org.apache.poi.xwpf.usermodel.*; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRow; public class WordInsertTableRow { public static void main(String[] args) throws Exception { XWPFDocument doc = new XWPFDocument(new FileInputStream("source.docx")); XWPFTable table = doc.getTableArray(0); //insert new row, which is a copy of row 2, as new row 3: XWPFTableRow oldRow = table.getRow(1); CTRow ctrow = CTRow.Factory.parse(oldRow.getCtRow().newInputStream()); XWPFTableRow newRow = new XWPFTableRow(ctrow, table); int i = 1; for (XWPFTableCell cell : newRow.getTableCells()) { for (XWPFParagraph paragraph : cell.getParagraphs()) { for (XWPFRun run : paragraph.getRuns()) { run.setText("New row 3 cell " + i++, 0); } } } table.addRow(newRow, 2); //insert new last row, which is a copy previous last row: XWPFTableRow lastRow = table.getRows().get(table.getNumberOfRows() - 1); ctrow = CTRow.Factory.parse(lastRow.getCtRow().newInputStream()); newRow = new XWPFTableRow(ctrow, table); i = 1; for (XWPFTableCell cell : newRow.getTableCells()) { for (XWPFParagraph paragraph : cell.getParagraphs()) { for (XWPFRun run : paragraph.getRuns()) { run.setText("New last row cell " + i++, 0); } } } table.addRow(newRow); doc.write(new FileOutputStream("result.docx")); doc.close(); } }