Search code examples
javatemplatesdata-bindingapache-poidocx

Populate docx table using List of Objects in java


I am trying to populate a table within a docx file with data from java objects. More precisely each row represents an Object and my pattern starts with one row. I want to find out how can I introduce a new row in case I have more than one objects in my list. See example below: Docx table looks like this:

enter image description here

And I successfully realized the mapping with the fields but for ONLY one object. How can i introduce another row (from Java) to make room for another object ? For this implementation I am using org.apache.poi.xwpf.usermodel.XWPFDocument;


public class DocMagic {

    public static XWPFDocument replaceTextFor(XWPFDocument doc, String findText, String replaceText) {
        replaceTextFor(doc.getParagraphs(),findText,replaceText);

        doc.getTables().forEach(p -> {
            p.getRows().forEach(row -> {
                row.getTableCells().forEach(cell -> {
                    replaceTextFor(cell.getParagraphs(), findText, replaceText);
                });
            });

        });
        return doc;
    }

    private static void replaceTextFor(List<XWPFParagraph> paragraphs, String findText, String replaceText) {
        paragraphs.forEach(p -> {
            p.getRuns().forEach(run -> {
                String text = run.text();
                if (text.contains(findText)) {
                    run.setText(text.replace(findText, replaceText), 0);
                }
            });
        });
    }

    public static void saveWord(String filePath, XWPFDocument doc) throws FileNotFoundException, IOException {
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(filePath);
            doc.write(out);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            out.close();
        }
    }
}

EDIT: using addNewTableCell().setText() places the values on the right side of the table enter image description here


Solution

  • Normally you use below steps to add row in a table,

    XWPFTableRow row =tbl.createRow();
    
    row.addNewTableCell().setText("whatever you want");
    
    tbl.addRow(row, y);
    

    But in your case seems you want to add rows on the fly while you are iterating the docx table together with your Java list of object,

    In Java your are not safe or able to change the collection while looping it, so you might need to do it in 2 steps,

    1. you need to expand/add rows first to the docx table before you populate it, by firstly calculate how many objects you have in your java list.
    2. when the table rows are already added accordingly, you could iterate and populate them