En este post vamos a ver cómo podemos copiar una tabla que tenemos en un documento Word plantilla, e incluirlo en nuestro documento final que queremos crear.
En este ejemplo, la tabla tiene una primera fila que es la cabecera y otra fila que sería la que tenemos que ir replicando para crear diferentes filas.
En este ejemplo, la tabla tiene una primera fila que es la cabecera y otra fila que sería la que tenemos que ir replicando para crear diferentes filas.
try (XWPFDocument document = new XWPFDocument(new FileInputStream(documentFile));
XWPFDocument tableDocument = new XWPFDocument(new FileInputStream(tableFile))) {
XWPFTable table = document.createTable();
table.removeRow(0); //This default row is not needed
XWPFTable tableDocument = tableDocument.getTables().get(0);
//Copy the table header
table.addRow(tableDocument.getRow(0));
//Add rows
XWPFTableRow row = tableDocument.getRow(1); //Copy the row style
addRow(table, row, "col1", "col2", "col3";
}
}
///...
private static void addRow(XWPFTable table, XWPFTableRow row, String... colTexts) {
for (int col = 0; col<colTexts.length; col++) {
row.getCell(col).getParagraphArray(0).getRuns().get(0).setText(colTexts[col], 0);
}
table.addRow(row);
}