java使用easypoi模版导出word详细步骤

文章目录

第一步、引入pom依赖

xml 复制代码
<dependency>
     <groupId>cn.afterturn</groupId>
     <artifactId>easypoi-spring-boot-starter</artifactId>
     <version>4.4.0</version>
</dependency>

第二步、新建导出工具类WordUtil

java 复制代码
import cn.afterturn.easypoi.word.WordExportUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Map;

@Component
@Slf4j
public class WordUtil {

    /**
     * 导出word
     * 模版变量中变量格式:{{a}}
     *
     * @param templatePath word模板地址
     * @param fileName     文件名
     * @param params       替换的参数
     * @param response     响应头
     * 
     */
    public static void exportWord(String templatePath, String fileName, Map<String, Object> params, HttpServletResponse response) {
        Assert.notNull(templatePath, "模板路径不能为空");
        Assert.notNull(fileName, "导出文件名不能为空");
        Assert.isTrue(fileName.endsWith(".docx"), "word导出请使用docx格式");

        try {
            XWPFDocument doc = WordExportUtil.exportWord07(templatePath, params);
            //设置响应体内容类型
            response.setContentType("application/octet-stream");
            //添加响应头
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            //暴露新添加的响应头
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            //将word文档流输出到输出流中
            doc.write(response.getOutputStream());
            //关闭流
            doc.close();
        } catch (Exception e) {
            log.error("exportWord方法出现问题", e);
            e.printStackTrace();
        }
    }

}

第三步、创建模版word

在静态资源目录下resources/static/templates新建exportWord.docx,编写以下模版内容:

4.编写接口代码

java 复制代码
    @GetMapping("/exportWord")
    public void exportWord(HttpServletResponse response) throws FileNotFoundException {
        //存放数据,也就是填充在word里面的值
        Map<String, Object> params = new HashMap<>();
        params.put("ceshi","测试使用easypoi模版导出word");
        params.put("name","张三");
        params.put("text","知之为知之不知为不知");

        //模板路径
        // String templatePath = "E:\\demo\\word.docx";
        // 或模板在静态资源的相对路径
        File rootFile = new File((ResourceUtils.getURL("classpath:").getPath()));
        File templateFile = new File(rootFile, "/static/templates/exportWord.docx");
        //jar包获取不到文件路径
        //URLDecoder.decode() 解决获取中文名称文件路径乱码
        String templatePath = URLDecoder.decode(templateFile.getPath());
        //生成文件名
        String fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + "_" + System.currentTimeMillis() + ".docx";
        // 导出wold
        try {
            // 导出Word文档为文件
           WordUtil.exportWord(templatePath, fileName, params,response);
            // 将导出的Word文件转换为流
        } catch (Exception e) {
            System.out.println("导出Word文档时出现异常:" + e.getMessage());
        }
    }

5.导出结果示例

通过浏览器访问接口:http://localhost:8080//exportWord,导出word内容如下

相关推荐
吃海鲜的骆驼4 分钟前
服务异步通讯与RabbitMQ
java·分布式·后端·rabbitmq
羱滒8 分钟前
sql调优之数据库开发规范
java·数据库·数据库开发
Forget the Dream36 分钟前
设计模式之责任链模式
java·c++·设计模式·责任链模式
jonyleek40 分钟前
「JVS更新日志」低代码、企业会议、智能BI、智能排产2.26更新说明
java·大数据·低代码·数据分析·软件需求
Joey_friends40 分钟前
【Linux】线程详解
开发语言
_GR1 小时前
Qt开发⑧Qt的窗口_下_浮动窗口+对话框
开发语言·css·c++·qt·microsoft
Good Note1 小时前
Golang——常用库context和runtime
开发语言·爬虫·golang
计算机小白一个1 小时前
蓝桥杯 Java B 组之最短路径算法(Dijkstra、Floyd-Warshall)
java·数据结构·算法·蓝桥杯
曼岛_1 小时前
[密码学实战]Java实现SM4加解密(ecb,cbc)及工具验证
java·密码学
清河__1 小时前
【Go】十七、grpc 服务的具体功能编写
开发语言·后端·golang