根据已有word文档模板生成word文档
import org.apache.poi.xwpf.usermodel.*;

import java.io.FileInputStream;
import java.io.FileOutputStream;

public class GenerateWordFromTemplate {

    public static void main(String[] args) {
        try {
            // 读取现有的 Word 文档模板
            FileInputStream fis = new FileInputStream("template.docx");
            XWPFDocument templateDoc = new XWPFDocument(fis);
            fis.close();

            // 创建新的 Word 文档
            XWPFDocument newDoc = new XWPFDocument();

            // 复制模板文档中的内容到新文档
            for (XWPFParagraph para : templateDoc.getParagraphs()) {
                XWPFParagraph newPara = newDoc.createParagraph();
                newPara.getCTP().set(para.getCTP());
            }

            for (XWPFTable table : templateDoc.getTables()) {
                XWPFTable newTable = newDoc.createTable();
                newTable.getCTTbl().set(table.getCTTbl());
            }

            // 写入新文档到文件
            FileOutputStream out = new FileOutputStream("new_document.docx");
            newDoc.write(out);
            out.close();

            System.out.println("新文档生成成功!");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
生成word文档,如何在word文档某个段落之后,新建一个段落
import org.apache.poi.xwpf.usermodel.*;

import java.io.*;

public class WordDocumentGenerator {

    public static void main(String[] args) {
        try {
            // 创建新文档对象
            XWPFDocument document = new XWPFDocument();

            // 创建一个段落
            XWPFParagraph paragraph1 = document.createParagraph();
            XWPFRun run1 = paragraph1.createRun();
            run1.setText("这是第一个段落。");

            // 创建一个段落
            XWPFParagraph paragraph2 = document.createParagraph();
            XWPFRun run2 = paragraph2.createRun();
            run2.setText("这是第二个段落。");

            // 在第一个段落之后插入一个新段落
            insertNewParagraphAfter(document, paragraph1);

            // 保存文档
            FileOutputStream out = new FileOutputStream("generated_document.docx");
            document.write(out);
            out.close();

            System.out.println("Word 文档生成成功!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 在指定段落之后插入一个新段落
    private static void insertNewParagraphAfter(XWPFDocument document, XWPFParagraph existingParagraph) {
        XWPFParagraph newParagraph = document.insertNewParagraph(existingParagraph.getCTP().newCursor());
        XWPFRun run = newParagraph.createRun();
        run.setText("这是新插入的段落。");
    }
}