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即可导出成功

相关推荐
前端与小赵2 分钟前
快速生成安卓证书并打包生成安卓apk(保姆教程)
android·前端
代码熬夜敲Q6 分钟前
网络工程相关
linux·服务器·网络
我登哥MVP7 分钟前
Spring Boo从“会用”到“精通”:Spring Boot 入门
java·spring boot·后端·spring·maven·intellij-idea·mybatis
Cxiaomu8 分钟前
MentorPi A1 底盘接入开发实践:让自研Web系统接管机器人底盘
前端·机器人
染翰12 分钟前
Java 实现 Git 自动克隆工具,打包成 Windows 独立 EXE(免安装JDK)
java·git·后端
七老板的blog20 分钟前
多阶段 AI 评测流水线架构设计与实践
java·人工智能·spring
开压路机23 分钟前
基础IO
linux·运维·服务器
qq_4581482025 分钟前
科大讯飞实时语音识别(rtasr)真实项目踩坑经验总结与手把手教学真实可运行Demo
java·开发语言·websocket·语音识别
创业之路&下一个五年29 分钟前
mvvm中v和vm关系,vm中v和m的关系?
java·开发语言·javascript
阿昌喜欢吃黄桃29 分钟前
Java优质开源AI项目
java·ai·langchain·开源·rag·springai·langchain4j