alibaba EasyExcel 简单导出数据到Excel

导入依赖

java 复制代码
<dependency>
     <groupId>com.alibaba</groupId>
     <artifactId>easyexcel</artifactId>
     <version>4.0.1</version>
</dependency>

1、alibaba.excel.EasyExcel导出工具类

java 复制代码
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.List;

public class ExcelUtil {

    /**
     * 导出excel
     *
     * @param response 响应
     * @param list 数据集
     * @param clazz 类名
     * @param fileName 文件名
     * @return
     */
    public static<T> void exportExcel(HttpServletResponse response, List<T> list, Class<T> clazz, String fileName) {
        try {
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8") + ".xlsx");
            EasyExcel.write(response.getOutputStream(), clazz)
                    .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())//自适应表格格式
                    .sheet("sheet1")
                    .doWrite(list);
        }catch (Exception e){
            throw new RuntimeException(e.getMessage());
        }
    }
}

2、controller层

java 复制代码
   @GetMapping("/export")
    public void exportExcel(HttpServletResponse response,OpreationLogEntity opreationLogEntity){
        List<OpreationLogEntity> oprLogList = opreationLogService.findOprLogList(opreationLogEntity);
        ExcelUtil.exportExcel(response,oprLogList,OpreationLogEntity.class,"系统日志");
    }

3、实体类字段加上注解:

(1)@ExcelIgnore:表示忽略导出该字段数据

(2)@ExcelProperty("账号"):导出对应的字段数据,并且设置Excel属性表头名,

举例--对应的表头名为:账号

(3)不加注解:例如sysModule字段,会导出该数据,但是表头名为sysModule

java 复制代码
@Data
public class OpreationLogEntity{

    @ExcelIgnore
    private Long id;

    @ExcelProperty("账号")
    private String opreCode;

    private String sysModule;
}

3、测试:浏览器地址栏输入url即可导出成功

相关推荐
Moment11 小时前
Vibe Coding 时代,到底该选什么样的工具来提升效率❓❓❓
前端·后端·github
IT_陈寒13 小时前
SpringBoot性能飙升200%?这5个隐藏配置你必须知道!
前端·人工智能·后端
小时前端13 小时前
React性能优化的完整方法论,附赠大厂面试通关技巧
前端·react.js
Nicko14 小时前
Jetpack Compose BOM 2026.02.01 解读与升级指南
前端
小蜜蜂dry14 小时前
nestjs学习 - 控制器、提供者、模块
前端·node.js·nestjs
优秀稳妥的JiaJi14 小时前
基于腾讯地图实现电子围栏绘制与校验
前端·vue.js·前端框架
前端开发呀14 小时前
从 qiankun(乾坤) 迁移到 Module Federation(模块联邦),对MF只能说相见恨晚!
前端
没想好d15 小时前
通用管理后台组件库-10-表单组件
前端
恋猫de小郭15 小时前
你用的 Claude 可能是虚假 Claude ,论文数据告诉你,Shadow API 中的欺骗性模型声明
前端·人工智能·ai编程
_Eleven15 小时前
Pinia vs Vuex 深度解析与完整实战指南
前端·javascript·vue.js