使用 EasyPoi 快速导出 Word 文档

EasyPoi 是一个基于 Apache POI 的开源 Java 工具库,旨在简化 Excel 和 Word 文档的操作。本文将详细介绍如何使用 EasyPoi 快速导出 Word 文档。

一、准备工作

1、引入依赖

在 Maven 项目中,添加以下依赖:

xml 复制代码
<dependency>
    <groupId>cn.afterturn</groupId>
    <artifactId>easy-poi-base</artifactId>
    <version>4.4.0</version>
</dependency>
<dependency>
    <groupId>cn.afterturn</groupId>
    <artifactId>easy-poi-annotation</artifactId>
    <version>4.4.0</version>
</dependency>

二、准备好一个word模版文件

  1. 在项目的 resources 目录下创建一个 template/exportTemplate.docx 文件作为模板。

  2. 使用 EasyPoi 提供的占位符 {{}} 来定义动态内容的位置。例如:

css 复制代码
{{title}}
{{content}}

三、编写导出方法的工具类

java 复制代码
package com.example.simple.util;


import cn.afterturn.easypoi.cache.manager.POICacheManager;
import cn.afterturn.easypoi.word.WordExportUtil;
import cn.afterturn.easypoi.word.entity.MyXWPFDocument;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.util.Map;

@Slf4j
public class ExportWordUtil {

    /**
     * 通用Word文档导出方法
     * @param templateName 模板文件名
     * @param params 模板参数
     * @param response HTTP响应对象
     * @param outputFileName 输出文件名
     * @throws RuntimeException 导出过程中的异常
     */
    public static void exportWordDocument(String templateName, Map<String, Object> params,
                                          HttpServletResponse response, String outputFileName) {
        MyXWPFDocument doc = null;
        try {
            // 获取模板文档
            doc = getXWPFDocument(templateName);
            if (doc == null) {
                throw new RuntimeException("未能找到模板文件");
            }

            // 使用模板引擎替换内容
            WordExportUtil.exportWord07(doc, params);

            // 设置响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
            response.setHeader("Content-Disposition", "attachment;filename=" + outputFileName);

            // 输出文档
            try (ServletOutputStream outputStream = response.getOutputStream()) {
                doc.write(outputStream);
                outputStream.flush();
            }
        } catch (Exception e) {
            log.error("导出Word文档失败", e);
            throw new RuntimeException("导出Word文档失败: " + e.getMessage());
        } finally {
            // 关闭文档
            if (doc != null) {
                try {
                    doc.close();
                } catch (Exception e) {
                    log.error("关闭文档失败", e);
                }
            }
        }
    }


    public static MyXWPFDocument getXWPFDocument(String templateName) throws IOException {
        // 从classpath获取模板
        InputStream is = null;
        try {
            is = POICacheManager.getFile(templateName);
            if (is == null) {
                throw new FileNotFoundException("模板文件不存在: " + templateName);
            }
            return new MyXWPFDocument(is);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    log.error("关闭输入流失败", e);
                }
            }
        }
    }
}

四、在ExportWordServiceImpl层调用导出word工具方法

注意:在spring-boot3中使用时response引入的是import jakarta.servlet.http.HttpServletResponse;

java 复制代码
@Override
    public void exportWord(Map<String, Object> map, HttpServletResponse response) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("title", "我是一个好标题");
        params.put("content", "我是一个很有深度的内容");
        ExportWordUtil.exportWordDocument("template/exportTemplate.docx", params, response, "export.docx");
    }

五、前端请求接口后word文档的展示效果

六、总结

通过 EasyPoi,我们可以轻松实现 Word 文档的导出功能。希望本文能帮助你快速上手并完成相关开发任务!

如果你有任何问题或建议,欢迎留言交流!

相关推荐
摇滚侠2 小时前
Spring Boot 3零基础教程,WEB 开发 静态资源默认配置 笔记27
spring boot·笔记·后端
天若有情6735 小时前
Java Swing 实战:从零打造经典黄金矿工游戏
java·后端·游戏·黄金矿工·swin
一只叫煤球的猫5 小时前
建了索引还是慢?索引失效原因有哪些?这10个坑你踩了几个
后端·mysql·性能优化
magic334165637 小时前
Springboot整合MinIO文件服务(windows版本)
windows·spring boot·后端·minio·文件对象存储
开心-开心急了7 小时前
Flask入门教程——李辉 第一、二章关键知识梳理(更新一次)
后端·python·flask
掘金码甲哥7 小时前
调试grpc的哼哈二将,你值得拥有
后端
小学鸡!7 小时前
Spring Boot实现日志链路追踪
java·spring boot·后端
用户21411832636029 小时前
OpenSpec 实战:用规范驱动开发破解 AI 编程协作难题
后端
Olrookie9 小时前
若依前后端分离版学习笔记(二十)——实现滑块验证码(vue3)
java·前端·笔记·后端·学习·vue·ruoyi
LucianaiB10 小时前
招聘可以AI面试,那么我制作了一个AI面试教练不过分吧
后端