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


相关推荐
xiaohe0717 分钟前
Maven Spring框架依赖包
java·spring·maven
不吃香菜学java33 分钟前
苍穹外卖-菜品分页查询
数据库·spring boot·tomcat·log4j·maven·mybatis
hssfscv35 分钟前
软件设计师下午题二 E-R图
java·笔记·学习
cyforkk39 分钟前
Spring Boot 3 集成 Swagger 踩坑实录:解决 doc.html 404 与 Unauthorized 拦截
spring boot·后端·html
十七号程序猿43 分钟前
Java图书管理系统 | 无需配置任何环境,双击一键启动,开箱即用
java·spring boot·vue·毕业设计·毕设·源代码管理
宝耶1 小时前
Java面试2:final、finally、finalize 的区别?
java·开发语言·面试
umeelove351 小时前
Spring boot整合quartz方法
java·前端·spring boot
yige451 小时前
SpringBoot 集成 Activiti 7 工作流引擎
java·spring boot·后端
dreamxian1 小时前
苍穹外卖day10
java·开发语言·spring boot
honor_zhang1 小时前
Spring Boot集成Websocket服务以及连接时需要注意的问题
spring boot·后端·websocket