Java使用easypoi填充数据到word

需要引入的Maven依赖

xml 复制代码
<dependency>
    <groupId>cn.afterturn</groupId>
    <artifactId>easypoi-base</artifactId>
    <version>4.4.0</version>
</dependency>
<dependency>
    <groupId>cn.afterturn</groupId>
    <artifactId>easypoi-web</artifactId>
    <version>4.4.0</version>
</dependency>
<dependency>
    <groupId>cn.afterturn</groupId>
    <artifactId>easypoi-annotation</artifactId>
    <version>4.4.0</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>4.1.1</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>4.1.1</version>
</dependency>

工具类(可直接使用或适当修改)

java 复制代码
import cn.afterturn.easypoi.word.WordExportUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Map;

public class FileUtil {

    public static void exportWordByModel(HttpServletResponse response, Map<String, Object> map, String modelFileName, String outFileName) {
        try {
            // 1.获取模板文件路径 - 重点
            //XWPFDocument word = WordExportUtil.exportWord07(modelFileName, map);有时候这种方式可以找到有时候找不到(不太清楚)
            String templatePath = filePath(modelFileName).getAbsolutePath();

            // 打印出模板文件的完整路径 - 校验路径是否存在
            File templateFile = new File(templatePath);
            if (templateFile.exists()) {
                System.out.println("模板文件存在: " + templateFile.getAbsolutePath());
            } else {
                System.out.println("模板文件不存在: " + templateFile.getAbsolutePath());
            }
            // 2.映射模板,替换数据
            XWPFDocument word = WordExportUtil.exportWord07(templatePath, map);
            // 3.设置返回参数的字符集
            response.reset();
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setContentType("application/msexcel");
            response.setContentType("text/html; charset=UTF-8");
            // 4.设置响应类型为Word文档
            response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
            // 5.中文文件名处理,否则报错
            String encodedFileName = URLEncoder.encode(outFileName, "UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + encodedFileName + ".docx");
            // 6.将Word文档发送到浏览器
            word.write(response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据文件名获取文件对象
     * @param modelFileName
     * @return
     */
    public static File filePath(String modelFileName) {
        // 获取类加载器
        ClassLoader classLoader = FileUtil.class.getClassLoader();
        // 尝试从类路径中加载资源
        URL resource = classLoader.getResource(modelFileName);
        return new File(resource.getFile());
    }
}

导出和填充接口实现

java 复制代码
import cn.afterturn.easypoi.entity.ImageEntity;
import com.etoak.system.model.ExamInfo;
import com.etoak.system.model.StuInfoBase;
import com.etoak.system.model.TeaOfStuInfo;
import com.etoak.system.service.StuService;
import com.etoak.system.utils.FileUtil;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/stu")
public class StuController {

    @Autowired
    StuService stuService;

    @GetMapping("/exportWord")
    public void exportWord(@RequestParam String stuNo, HttpServletResponse response){
        HashMap<String,Object> map = new HashMap<>();

        String picPath1 = "https://tse2-mm.cn.bing.net/th/id/OIP-C.o3n2zlSej1hWPJkQPJ9l1AHaE8?w=274&h=183&c=7&r=0&o=7&dpr=1.1&pid=1.7&rm=3";
        ImageEntity imageEntity1 = new ImageEntity();
        imageEntity1.setUrl(picPath1);
        imageEntity1.setWidth(50);
        imageEntity1.setHeight(60);

        imageEntity1.setType(ImageEntity.URL);
        map.put("pictureVar1", imageEntity1);

        String picPath2 = "D:\\upload\\et2503\\9be44def628648b398205190a09979a9.png";
        ImageEntity imageEntity2 = new ImageEntity();
        imageEntity2.setUrl(picPath2);
        imageEntity2.setWidth(50);
        imageEntity2.setHeight(60);

        imageEntity2.setType(ImageEntity.URL);
        map.put("pictureVar2", imageEntity2);



        StuInfoBase stuInfoBase = stuService.getStuInfoByStuNo(stuNo);
        map.put("name",stuInfoBase.getName());
        map.put("stuNo",stuInfoBase.getStuNo());
        map.put("gender",stuInfoBase.getGender()==0?"男":"女");
        map.put("height",stuInfoBase.getHeight());
        map.put("weight",stuInfoBase.getWeight());
        map.put("bloodType",stuInfoBase.getBloodType());

        List<ExamInfo> examInfos = stuService.getExamInfoListByStuNo(stuNo);
        map.put("examInfos",examInfos);

        FileUtil.exportWordByModel(response,map,"templates/word.docx","学生信息统计");
    }

}

word导出前后对比


相关推荐
caimo7 分钟前
Java无法访问网址出现Timeout但是浏览器和Postman可以
java·开发语言·postman
Deamon Tree16 分钟前
ElasticSearch架构和写入、更新、删除、查询的底层逻辑
java·大数据·elasticsearch·架构
一 乐36 分钟前
商城推荐系统|基于SprinBoot+vue的商城推荐系统(源码+数据库+文档)
前端·数据库·vue.js·spring boot·后端·商城推荐系统
北极糊的狐39 分钟前
IntelliJ IDEA插件:CodeGeeX 智能助手插件
java·ide·intellij-idea
悟能不能悟41 分钟前
jdk25结构化并发和虚拟线程如何配合使用?有什么最佳实践?
java·开发语言
熙客1 小时前
Java8:Lambda表达式
java·开发语言
小咕聊编程1 小时前
【含文档+PPT+源码】基于java web的篮球馆管理系统系统的设计与实现
java·开发语言
后端小张1 小时前
【JAVA 进阶】Mybatis-Plus 实战使用与最佳实践
java·spring boot·spring·spring cloud·tomcat·mybatis·mybatis plus
崎岖Qiu1 小时前
【设计模式笔记07】:迪米特法则
java·笔记·设计模式·迪米特法则
摇滚侠3 小时前
Spring Boot3零基础教程,SpringApplication 自定义 banner,笔记54
java·spring boot·笔记