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导出前后对比


相关推荐
专注VB编程开发20年9 分钟前
C#全面超越JAVA,主要还是跨平台用的人少
java·c#·.net·跨平台
南_山无梅落26 分钟前
9.Python3集合(set)增删改查和推导式
java·开发语言
爱笑的眼睛1142 分钟前
超越MSE与交叉熵:深度解析损失函数的动态本质与高阶设计
java·人工智能·python·ai
全靠bug跑1 小时前
Spring Cloud OpenFeign 实战三部曲:快速集成 · 连接池优化 · 客户端抽取
java·spring boot·openfeign
Evan芙1 小时前
搭建nexus服务,实现本地仓库、代理仓库
java·nginx·tomcat
乂爻yiyao1 小时前
Java LTS版本重要升级特性对照表
java·开发语言
原来是好奇心2 小时前
深入Spring Boot源码(六):Actuator端点与监控机制深度解析
java·开发语言·源码·springboot
北城以北88882 小时前
Spring定时任务与Spring MVC拦截器
spring boot·spring·mvc
缘不易2 小时前
Springboot 整合JustAuth实现gitee授权登录
spring boot·后端·gitee