当前位置:   article > 正文

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

java根据word模板生成word文档

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

一、新建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
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

三、编写代码

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);
                    }
                }
            }
        }
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55

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

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));
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55

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


声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/木道寻08/article/detail/1014601
推荐阅读
相关标签
  

闽ICP备14008679号