easyExcel - 根据模板文件导出

废话不多说!!!直接上代码 复制粘贴即可

如有不懂:先参考官方文档

EasyExcel官方文档 - 基于Java的Excel处理工具 | Easy Excel (alibaba.com)

针对模板文件:

占位符用 {变量} 表示,比如 {name}{age} 一条数据

占位符为列表,则使用 {.变量} 表示,比如:{.name}{.age} 多条数据

这个变量需要和你的实体类字段一致哈..别整差咯..

本地代码如下:

java 复制代码
public void studentList() {
        // 模板文件路径
        String templateFilePath = "D:\\excel\\tingyi-template.xlsx";
        // 输出文件路径
        String outFilePath = "D:\\excel\\tingyi.xlsx";

        // 创建 ExcelWriter 实例
        ExcelWriter writer = EasyExcel
                // 写入到
                .write(outFilePath)
                // 指定模板
                .withTemplate(templateFilePath)
                .build();

        WriteSheet sheet = EasyExcel.writerSheet().build();

        // 上数据库查你所需的数据即可

        FillConfig fillConfig = FillConfig.builder()
                // 开启填充换行
                .forceNewRow(true)
                .build();

        // 执行填充操作
        writer.fill(查出的数据, fillConfig, sheet);

        // 结束
        writer.finish();
    }

实际应用开发代码如下(就是你在公司要写的代码):

java 复制代码
@Operation(description = "下载表格")
    @PostMapping("/import")
    public void excelimport(HttpServletResponse response, @RequestBody List<LandOfTheStatus> ofTheStatuses) throws IOException {
        // 模板文件路径
        String templateFilePath = landOfStatusFile;
        response.reset();
        response.setCharacterEncoding("UTF-8");
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("听忆Excel导出.xlsx", "UTF-8"));
        response.setContentType("application/octet-stream");

        // 创建 ExcelWriter 实例
        ExcelWriter writer = EasyExcel
                // 写入到
                .write(response.getOutputStream())
                // 指定模板
                .withTemplate(templateFilePath)
                .build();

        WriteSheet sheet = EasyExcel.writerSheet().build();
                //这里应该是查询你所要导出的数据  我这么图方便,直接传了list
        FillConfig fillConfig = FillConfig.builder()
                // 开启填充换行
                .forceNewRow(true)
                .build();

        //计算公式  比如你模板文件里设定了一些公式  加减乘除等等  会自动计算
        Workbook workbook = writer.writeContext().writeWorkbookHolder().getWorkbook();
        workbook.setForceFormulaRecalculation(true);
        // 执行填充操作
        writer.fill(ofTheStatuses, fillConfig, sheet);

        // 结束
        writer.finish();


    }
相关推荐
Cikiss几秒前
微服务实战——平台属性
java·数据库·后端·微服务
无敌の星仔9 分钟前
一个月学会Java 第2天 认识类与对象
java·开发语言
OEC小胖胖14 分钟前
Spring Boot + MyBatis 项目中常用注解详解(万字长篇解读)
java·spring boot·后端·spring·mybatis·web
小小不董14 分钟前
《Linux从小白到高手》理论篇:深入理解Linux的网络管理
linux·运维·服务器·数据库·php·dba
豆豆32 分钟前
为什么用PageAdmin CMS建设网站?
服务器·开发语言·前端·php·软件构建
2401_8576176238 分钟前
SpringBoot校园资料平台:开发与部署指南
java·spring boot·后端
quokka5641 分钟前
Springboot 整合 logback 日志框架
java·spring boot·logback
无敌少年小旋风1 小时前
MySQL 内部优化特性:索引下推
数据库·mysql
计算机学姐1 小时前
基于SpringBoot+Vue的在线投票系统
java·vue.js·spring boot·后端·学习·intellij-idea·mybatis
柒小毓1 小时前
将excel导入SQL数据库
数据库