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实现身份证号码验证源码示例分享

    Java实现身份证号码验证源码示例分享

    本篇文章主要介绍了Java实现身份证号码验证源码示例分享,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-10-10
  • springboot下使用mybatis的方法

    springboot下使用mybatis的方法

    这篇文章主要介绍了springboot下使用mybatis的方法,需要的朋友可以参考下
    2017-11-11
  • 详解spring cloud hystrix请求缓存(request cache)

    详解spring cloud hystrix请求缓存(request cache)

    这篇文章主要介绍了详解spring cloud hystrix请求缓存(request cache),小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-05-05
  • Java Floyd算法求有权图(非负权)的最短路径并打印

    Java Floyd算法求有权图(非负权)的最短路径并打印

    这篇文章主要介绍了Java Floyd算法求有权图(非负权)的最短路径并打印,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-07-07
  • SpringBoot依赖管理特性详解

    SpringBoot依赖管理特性详解

    Spring Boot自动引入依赖的版本信息可以在`spring-boot-starter-parent`和`spring-boot-dependencies`的pom文件中找到,如果需要修改依赖版本,可以在项目pom文件中添加覆盖配置项并刷新依赖即可
    2025-01-01
  • 详解Java的Spring框架中bean的定义以及生命周期

    详解Java的Spring框架中bean的定义以及生命周期

    这篇文章主要介绍了Java的Spring框架中bean的定义以及生命周期,bean的实例化是Java web开发中的重要基础,需要的朋友可以参考下
    2015-12-12
  • Spring Boot整合流控组件Sentinel的场景分析

    Spring Boot整合流控组件Sentinel的场景分析

    Sentinel 提供简单易用、完善的 SPI 扩展接口。您可以通过实现扩展接口来快速地定制逻辑,这篇文章主要介绍了Spring Boot整合流控组件Sentinel的过程解析,需要的朋友可以参考下
    2021-12-12
  • SpringBoot中的Bean的初始化与销毁顺序解析

    SpringBoot中的Bean的初始化与销毁顺序解析

    这篇文章主要介绍了SpringBoot中的Bean的初始化与销毁顺序,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-08-08
  • JavaMail实现带附件的邮件发送

    JavaMail实现带附件的邮件发送

    这篇文章主要为大家详细介绍了JavaMail实现带附件的邮件发送,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-08-08
  • 将本地jar包安装进入maven仓库(实现方法)

    将本地jar包安装进入maven仓库(实现方法)

    下面小编就为大家带来一篇将本地jar包安装进入maven仓库(实现方法)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-06-06

最新评论