java根据自定义的word模板生成文档

该文章介绍了如何使用Java的ApachePOI库来动态生成Word文档,包括替换模板中的文字占位符和在文档中插入图片。开发者首先创建一个包含占位符的Word模板,然后导入ApachePOI和相关依赖,编写代码遍历文档并替换占位符,最后插入图片并保存生成的文档。
摘要由CSDN通过智能技术生成

提示:以下是本篇文章正文内容,下面案例可供参考

一、新建Word模板

模板文档
在你需要动态生成的内容使用{field}作为占位符,后面代码扫描到就将占位符换成自己的动态内容。

二、导入依赖

  <dependency>
         <groupId>org.apache.poi</groupId>
         <artifactId>poi</artifactId>
         <version>4.1.2</version>
     </dependency>
     <dependency>
         <groupId>org.apache.poi</groupId>
         <artifactId>poi-ooxml</artifactId>
         <version>4.1.2</version>
     </dependency>

     <dependency>
         <groupId>commons-io</groupId>
         <artifactId>commons-io</artifactId>
         <version>2.11.0</version>
     </dependency>

三、编写代码

1、替换文字

代码如下(示例):

   public static void main(String[] args) {
        try {
            String templatePath = "C:\\Users\\Administrator\\Desktop\\test3.docx";
            String outputPath = "C:\\Users\\Administrator\\Desktop\\output.docx";

            InputStream inputStream = new FileInputStream(templatePath);
            XWPFDocument document = new XWPFDocument(inputStream);

            Map<String, String> hashMap = new HashMap<>();
            hashMap.put("name", "JUVENILESS");
            hashMap.put("gender", "男");
            hashMap.put("schoolNumber", "13123132");
            hashMap.put("qq", "123123");
            hashMap.put("nativePlace", "测试");
            hashMap.put("profession", "测试啊");
            hashMap.put("birth", "2025-10");
            hashMap.put("dorm", "I123");
            hashMap.put("cellNumber", "12345678911");
            hashMap.put("introduction", "简单的自我介绍");
            hashMap.put("futureOutlook", "简单的对未来发展");
            hashMap.put("award", "拿过的奖项拿过的奖项");
            hashMap.put("department","部门");
            hashMap.put("year","年份");
            // 替换占位符
            replacePlaceholdersInDocument(document, hashMap);

            // 插入图片
            insertPictureInTableCell(document, "{picture}", picturePath);

            // 保存生成的文档
            FileOutputStream outputStream = new FileOutputStream(outputPath);
            document.write(outputStream);
            outputStream.close();

            System.out.println("生成的文档已保存。");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void replacePlaceholdersInDocument(XWPFDocument document, Map<String, String> hashMap) {
        for (XWPFParagraph paragraph : document.getParagraphs()) {
            replaceParagraphPlaceholders(paragraph, hashMap);
        }

        for (XWPFTable table : document.getTables()) {
            for (XWPFTableRow row : table.getRows()) {
                for (XWPFTableCell cell : row.getTableCells()) {
                    for (XWPFParagraph paragraph : cell.getParagraphs()) {
                        replaceParagraphPlaceholders(paragraph, hashMap);
                    }
                }
            }
        }
    }

直接运行即可。运行结果图为:
结果图

2、插入图片

这里我是查找表格的单元格里的占位符。
图片文档模板

代码如下(示例):

static String picturePath = "C:\\Users\\Administrator\\Desktop\\picture.jpg";

  public static void main(String[] args) {

        try {
            String templatePath = "C:\\Users\\Administrator\\Desktop\\test4.docx";
            String outputPath = "C:\\Users\\Administrator\\Desktop\\output1.docx";

            InputStream inputStream = new FileInputStream(templatePath);
            XWPFDocument document = new XWPFDocument(inputStream);
            
            // 插入图片
            insertPictureInTableCell(document, "{picture}", picturePath);

            // 保存生成的文档
            FileOutputStream outputStream = new FileOutputStream(outputPath);
            document.write(outputStream);
            outputStream.close();
            System.out.println("生成的文档已保存。");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void insertPictureInTableCell(XWPFDocument document, String placeholder, String picturePath) throws Exception {
        List<XWPFTable> tables = new ArrayList<>(document.getTables());
        for (XWPFTable table : tables) {
            List<XWPFTableRow> rows = new ArrayList<>(table.getRows());
            for (XWPFTableRow row : rows) {
                List<XWPFTableCell> cells = new ArrayList<>(row.getTableCells());
                for (XWPFTableCell cell : cells) {
                    List<XWPFParagraph> paragraphs = new ArrayList<>(cell.getParagraphs());
                    for (XWPFParagraph paragraph : paragraphs) {
                        List<XWPFRun> runs = new ArrayList<>(paragraph.getRuns());
                        for (XWPFRun run : runs) {
                            String text = run.getText(0);
                            if (text != null && text.contains(placeholder)) {
                                int index = text.indexOf(placeholder);
                                if (index >= 0) {
                                    // 移除占位符
                                    run.setText(text.replace(placeholder, ""), 0);

                                    // 在当前段落中插入图片
                                    XWPFRun pictureRun = paragraph.createRun();
                                    try (FileInputStream pictureInputStream = new FileInputStream(picturePath)) {
                                        pictureRun.addPicture(pictureInputStream, Document.PICTURE_TYPE_JPEG, "picture.jpg", Units.toEMU(200), Units.toEMU(200));
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

生成的结果如下:
生成结果
这里我发现图片的尺寸没法保证跟单元格大小一致,也尝试过很多种方法都不太行。哪位大佬尝试尝试哈哈哈哈


  • 0
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 9
    评论
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值