easyexcel封装工具类以及简单使用方式

 更新时间:2026年02月05日 14:43:41   作者:哀愁  
文章介绍了如何使用封装工具类、控制器和实体类进行开发,并通过Postman进行测试,作者分享了个人经验,希望能对大家有所帮助
 <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>easyexcel</artifactId>
            <version>2.2.10</version>
        </dependency>

封装工具类

package com.lk.util;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.write.handler.WriteHandler;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author : lk
 * @date 2021/8/31 23:29
 **/
@Slf4j
public class ExcelUtil {


    public ExcelUtil() {
    }

    /**
     * 导出execl
     *
     * @param response 响应体
     * @param list     数据
     * @param clazz    类
     * @param <T>
     */
    public static <T> void downExcelUtil(HttpServletResponse response, List<T> list, Class<T> clazz) {
        String fileName = System.currentTimeMillis() + "";
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        try {
            int i = 0;
            if (!list.isEmpty()) {
                EasyExcel.write(response.getOutputStream(), clazz)
                        .registerWriteHandler(createTableStyle())
                        .sheet("data" + (i++))
                        .doWrite(list);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 文件上传
     * <p>
     * 1. 创建excel对应的实体对象
     * <p>
     * 2. 由于默认一行行的读取excel,所以需要创建excel一行一行的回调监听器,
     * <p>
     * 3. 直接读即可
     */

    public static <T> List<T> uploadExcel(MultipartFile file) throws IOException {

        final List<T> rows = new ArrayList<T>();
        ReadListener readListener = new AnalysisEventListener<T>() {
            @Override
            public void invoke(T data, AnalysisContext context) {
                rows.add(data);
            }

            @Override
            public void doAfterAllAnalysed(AnalysisContext context) {
                log.info("read {} rows", rows.size());
            }
        };
        EasyExcel.read(file.getInputStream(), null, readListener).sheet().doRead();
        return rows;

    }

    public static <T> List<T> uploadExcel(MultipartFile file, Class<T> tClass) throws IOException {
        final List<T> rowss = new ArrayList<T>();
        ReadListener readListener = new AnalysisEventListener<T>() {
            @Override
            public void invoke(T data, AnalysisContext context) {
                rowss.add(data);
            }

            @Override
            public void doAfterAllAnalysed(AnalysisContext context) {
                log.info("read {} rows", rowss.size());
            }
        };
        EasyExcel.read(file.getInputStream(), tClass, readListener).sheet().doRead();
        return rowss;

    }

    private static WriteHandler createTableStyle() {
        // 头的策略
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        // 背景设置为红色
        headWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
        // 设置字体
        WriteFont headWriteFont = new WriteFont();
        headWriteFont.setFontHeightInPoints((short) 10);
        headWriteFont.setBold(false);
        headWriteCellStyle.setWriteFont(headWriteFont);
        headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        // 内容的策略
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();

        WriteFont contentWriteFont = new WriteFont();
        // 字体大小
        contentWriteFont.setFontHeightInPoints((short) 10);
        contentWriteCellStyle.setWriteFont(contentWriteFont);

        // 这个策略是 头是头的样式 内容是内容的样式 其他的策略可以自己实现
        HorizontalCellStyleStrategy horizontalCellStyleStrategy =
                new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
        return horizontalCellStyleStrategy;
    }
}

控制器

package com.lk.controller;

import com.lk.model.Student;
import com.lk.util.ExcelUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author : lk
 * @date 2021/8/31 22:19
 **/
@RestController
@Slf4j
public class HelloController {
	// 导出模版
    @GetMapping("template")
    public void template(HttpServletResponse response) {

        ExcelUtil.downExcelUtil(response, new ArrayList<>(), Student.class);
    }
	// 上传文件
    @PostMapping("upload")
    public void test02(@RequestParam("file") MultipartFile file) {

        try {
            List<Object> objects = ExcelUtil.uploadExcel(file);

            log.info("studnets:{}", objects);


        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}

实体类

package com.lk.model;

import com.alibaba.excel.annotation.ExcelProperty;
import lombok.Data;

/**
 * @author : lk
 * @date 2021/8/31 22:19
 **/
@Data
public class Student {

    @ExcelProperty(value = "编号")
    private String id;

    @ExcelProperty(value = "学生姓名")
    private String name;

    @ExcelProperty(value = "年龄")
    private Integer age;
}

使用postman测试

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • Java下载Excel模板文件的简单实现方法

    Java下载Excel模板文件的简单实现方法

    这篇文章主要给大家介绍了关于Java下载Excel模板文件的简单实现方法,日常工作中可能经常会涉及到用java开发报表,需求比较多的就是表格类的报表导出,单元格合并,图表的展现,需要的朋友可以参考下
    2023-07-07
  • SpringBoot整合SQLite的超详细讲解

    SpringBoot整合SQLite的超详细讲解

    sqlite数据库是轻量化,易用的嵌入式数据库,用于设备端的数据管理,可以理解成单点的数据库,下面这篇文章主要给大家介绍了关于SpringBoot整合SQLite的超详细讲解,需要的朋友可以参考下
    2024-03-03
  • Java日期时间类(Date、DateFormat、Calendar)解析

    Java日期时间类(Date、DateFormat、Calendar)解析

    这篇文章主要介绍了Java日期时间类(Date、DateFormat、Calendar)解析,文章围绕主题展开详细的内容介绍,具有一定的参考价值,需要的小伙伴可以参考一下
    2022-06-06
  • 如何给yml配置文件的密码加密(SpringBoot)

    如何给yml配置文件的密码加密(SpringBoot)

    这篇文章主要介绍了如何给yml配置文件的密码加密(SpringBoot),具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-10-10
  • java新人基础入门之递归调用

    java新人基础入门之递归调用

    这篇文章主要给大家介绍了关于java新人基础入门之递归调用的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-02-02
  • Spring Boot深入分析讲解日期时间处理

    Spring Boot深入分析讲解日期时间处理

    项目中使用LocalDateTime系列作为DTO中时间的数据类型,但是SpringMVC收到参数后总报错,为了配置全局时间类型转换,尝试了如下处理方式
    2022-06-06
  • spring cloud 阿波罗 apollo 本地开发环境搭建过程

    spring cloud 阿波罗 apollo 本地开发环境搭建过程

    Apollo(阿波罗)是携程框架部门研发的配置管理平台,能够集中化管理应用不同环境、不同集群的配置,配置修改后能够实时推送到应用端,并且具备规范的权限、流程治理等特性
    2018-01-01
  • Spring Security配置多个数据源并添加登录验证码的实例代码

    Spring Security配置多个数据源并添加登录验证码的实例代码

    这篇文章主要介绍了Spring Security配置多个数据源并添加登录验证码,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2022-08-08
  • java 中 阻塞队列BlockingQueue详解及实例

    java 中 阻塞队列BlockingQueue详解及实例

    这篇文章主要介绍了java 中 阻塞队列BlockingQueue详解及实例的相关资料,需要的朋友可以参考下
    2017-03-03
  • SpringCloud实现全链路灰度发布的示例详解

    SpringCloud实现全链路灰度发布的示例详解

    灰度发布是指在软件或服务发布过程中,将新版本的功能或服务以较小的比例引入到生产环境中,仅向部分用户或节点提供新功能的一种发布策略,下面我们就来学习一下SpringCloud如何实现全链路灰度发布
    2023-11-11

最新评论