Java 根据模版生成word文档并下载

1.Maven 配置

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

2.创建word模版

新建person_template.docx,内容如下:

个人信息表
姓名:${name}
年龄:${age}
性别:${gender}

3.根据模版生成word文档并下载

    public void download(HttpServletResponse response) {
        try {
            String templateFilePath = "person_template.docx";
            XWPFDocument document = new XWPFDocument(new FileInputStream(templateFilePath));
            Map<String, String> placeholderMap = new HashMap<>();
            placeholderMap.put("${name}", "小李");
            placeholderMap.put("${age}", "18");
            placeholderMap.put("${gender}", "男");
            for (XWPFParagraph paragraph : document.getParagraphs()) {
                for (XWPFRun run : paragraph.getRuns()) {
                    String text = run.getText(0);
                    if (text != null) {
                        for (Map.Entry<String, String> entry : placeholderMap.entrySet()) {
                            text = text.replace(entry.getKey(), entry.getValue());
                        }
                        String[] lines = text.split("\n");
                        if (lines.length > 1) {
                            for (int i = 0; i < lines.length; i++) {
                                if (i > 0) {
                                    run.addBreak();
                                    run.setText(lines[i]);
                                } else {
                                    run.setText(lines[i], 0);
                                }
                            }
                        } else {
                            run.setText(text, 0);
                        }
                    }
                }
            }
            response.setContentType("APPLICATION/OCTET-STREAM");
            String fileName = "person.docx";
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("UTF-8"), "ISO-8859-1"));
            OutputStream outputStream = response.getOutputStream();
            document.write(outputStream);
            document.close();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

 

posted @ 2026-03-20 15:18  root-crypto  阅读(0)  评论(0)    收藏  举报