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


相关推荐
亲爱的非洲野猪2 分钟前
从ReentrantLock到AQS:深入解析Java并发锁的实现哲学
java·开发语言
wheelmouse77884 分钟前
如何设置VSCode打开文件Tab页签换行
java·python
yangminlei6 分钟前
Spring Boot——日志介绍和配置
java·spring boot
云上凯歌10 分钟前
02 Spring Boot企业级配置详解
android·spring boot·后端
廋到被风吹走13 分钟前
【Spring】Spring Boot Starter设计:公司级监控SDK实战指南
java·spring boot·spring
码头整点薯条18 分钟前
启动报错:Invalid value type for attribute ‘factoryBeanObjectType‘ 解决方案
java
沛沛老爹18 分钟前
Web开发者进阶AI:Agent Skills-深度迭代处理架构——从递归函数到智能决策引擎
java·开发语言·人工智能·科技·架构·企业开发·发展趋势
工具罗某人21 分钟前
docker快速部署kafka
java·nginx·docker
秋饼23 分钟前
【手撕 @EnableAsync:揭秘 SpringBoot @Enable 注解的魔法开关】
java·spring boot·后端
Good_Starry26 分钟前
Java——正则表达式
java·开发语言·正则表达式