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


相关推荐
又是忙碌的一天3 小时前
java学习:四大排序
java·学习·排序算法
城管不管3 小时前
面试题(1)
java
二饭3 小时前
POI操作Docx的踩坑指南(一)
java·apache
李贺梖梖3 小时前
DAY25 综合案例
java
-雷阵雨-4 小时前
数据结构——优先级队列(堆)
java·开发语言·数据结构·intellij-idea
好家伙VCC4 小时前
**全息显示技术的发散创新与深度探索**一、引言随着科技的飞速发展,全息显示技术已成为显示领域的一大研究热点。本文将带你
java·图像处理·python·科技·计算机视觉
步行cgn4 小时前
Java项目包结构设计与功能划分详解
java·开发语言·架构·mvc
ss2734 小时前
手写MyBatis第92弹:SqlSource体系、SqlNode树与Trim标签实现原理全揭秘
java·开发语言
235165 小时前
【LeetCode】46. 全排列
java·数据结构·后端·算法·leetcode·职场和发展·深度优先