使用 java 中的对象列表填充 docx table

Populate docx table using List of Objects in java

我正在尝试使用 java 对象中的数据填充 docx 文件中的 table。更准确地说,每一行代表一个对象,我的模式从一行开始。我想知道如果我的列表中有多个对象,我该如何引入一个新行。请参见下面的示例: Docx table 看起来像这样:

而且我成功地实现了与字段的映射,但只针对一个对象。我如何引入另一行(来自 Java)来为另一个对象腾出空间?对于此实现,我使用 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();
        }
    }
}

编辑:使用 addNewTableCell().setText() 将值放在 table 的右侧

通常您使用以下步骤在 table、

中添加行
XWPFTableRow row =tbl.createRow();

row.addNewTableCell().setText("whatever you want");

tbl.addRow(row, y);

但在您的情况下,您似乎想在迭代 docx table 以及您的 Java 对象列表时动态添加行,

在 Java 中,您不安全或无法在循环时更改集合, 所以你可能需要分两步完成,

  1. 您需要先 expand/add 行到 docx table 然后再填充它, 首先计算 java 列表中有多少对象。
  2. 当 table 行已相应添加时,您可以迭代并填充它们