I am working with Apache POI to manipulate DOCX files and need to perform a specific task involving tables. I have a table in a DOCX file where each row has a varying number of columns. My goal is to copy each row from this table and append it as a new table below the original one, preserving the varying column structure as well as cell styling.
Here is the code I have, it currently just copies the text but does not maintain cell span, style or format.
XWPFTable frTable = document.getTables().get(1);
XWPFTable newTable = document.createTable();
for (int i = 0; i < frTable.getNumberOfRows(); i++) {
XWPFTableRow originalRow = frTable.getRow(i);
XWPFTableRow newRow = newTable.createRow();
// Iterate over cells
for (int j = 0; j < originalRow.getTableCells().size(); j++) {
XWPFTableCell originalCell = originalRow.getCell(j);
XWPFTableCell newCell = newRow.getCell(j);
if (newCell == null) {
newCell = newRow.addNewTableCell();
}
// Copy cell content
newCell.setText(originalCell.getText());
}
}
newTable.removeRow(0);
Here is the original table for reference:
Reference Table
peds24 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.