导入导出之使用EasyExcel快速进行表格导出

使用 EasyExcel 快速进行表格导入导出操作

在日常工作中,表格的导入和导出是常见的需求。针对这种情况,EasyExcel 提供了便捷的解决方案,可以快速地实现 Excel 表格的导入和导出操作。本文将介绍如何使用 EasyExcel 进行表格导出,以及如何利用 EasyExcel 的特性来简化这一过程。

1. 添加 EasyExcel 依赖

首先,需要在你的项目中添加 EasyExcel 的依赖。你可以通过 Maven 或 Gradle 将 EasyExcel 引入到项目中。以下是 Maven 依赖的示例:

复制代码
<dependency>  
    <groupId>com.alibaba</groupId>  
    <artifactId>easyexcel</artifactId>  
    <version>2.4.6</version> <!-- 使用最新版本 -->  
</dependency>  

2. 创建数据模型

在进行表格导出之前,首先需要创建一个数据模型类,用来表示你要导出的数据。这个数据模型类中可以使用 EasyExcel 提供的注解来标识 Excel 中的各个字段,以及指定一些特性,比如日期格式、转换器等。

实体类:需要导出的表格样式在这里使用注解设置,比如表格宽度高度字体颜色等

复制代码
package cn.ejar.cnos.management.system.api.response.usermeeting;

import cn.ejar.cnos.management.system.api.util.excel.GenderConverter;
import cn.ejar.cnos.management.system.api.util.excel.LocalDateTimeConverter;
import cn.ejar.cnos.management.system.api.util.excel.YesOrNotConverter;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.write.style.ColumnWidth;
import com.alibaba.excel.annotation.write.style.ContentRowHeight;
import com.alibaba.excel.annotation.write.style.HeadRowHeight;
import lombok.Data;

import java.io.Serial;
import java.io.Serializable;
import java.time.LocalDateTime;


@Data
@ContentRowHeight(20)
@HeadRowHeight(20)
@ColumnWidth(12)
public class UserMeetingVO implements Serializable {
	@Serial
	private static final long serialVersionUID = 3607872979830959632L;

	//用户账号
	@ExcelProperty("用户账号")
	private String mobile;

	/**
	 * 用户姓名
	 */
	@ExcelProperty("用户姓名")
	private String userName;

	/**
	 * 性别 1.男 2.女
	 */
	@ExcelProperty(value = "性别", converter = GenderConverter.class)
	private Integer sex;

	/**
	 * 联系电话
	 */
	@ExcelProperty("联系电话")
	private String phone;

	/**
	 * 所属机构
	 */
	@ExcelProperty("所属机构")
	private String affiliatedOrganization;

	/**
	 * 出行起点
	 */
	@ExcelProperty("出行起点")
	private String departurePoint;

	/**
	 * 出行方式
	 */
	@ExcelProperty("出行方式")
	private String travelMode;

	/**
	 * 是否需要住宿 1.是 2.否
	 */
	@ExcelProperty(value = "是否住宿",converter = YesOrNotConverter.class)
	private Integer isRequired;

	/**
	 * 预计住宿时间
	 */
	@ColumnWidth(17)
	@ExcelProperty("住宿时间(晚)")
	private Integer estimatedLengthOfStay;

	/**
	 * 报名时间
	 */
	@ColumnWidth(16)
	@ExcelProperty(value = "报名时间",converter = LocalDateTimeConverter.class)
	private LocalDateTime createTime;

	/**
	 * 是否签到 1.是 2.否
	 */
	@ExcelProperty(value = "是否签到",converter = YesOrNotConverter.class)
	private Integer isSignIn;

	/**
	 * 签到时间
	 */
	@ColumnWidth(16)
	@ExcelProperty(value = "签到时间",converter = LocalDateTimeConverter.class)
	private LocalDateTime signTime;

	/**
	 * 备注
	 */
	@ExcelProperty("备注")
	private String remark;
}

转换类:提供了很多的转换类共大家使用,也可以自定义转换类,比如有一些字段是使用枚举值存在数据库,但是导出的时候需要导出中文,这时候就可以指定转换器 以下是我的一个例子

复制代码
package cn.ejar.cnos.management.system.api.util.excel;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;


/**
 * 性别转换器
 *
 * @author Jerry
 * @date 2024/04/10
 */
public class GenderConverter implements Converter<Integer> {

    @Override
    public WriteCellData<?> convertToExcelData(Integer value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        //1.男 2.女
        if (value == null) {
            return new WriteCellData();
        } else if (value == 1) {
            return new WriteCellData("男");
        } else if (value == 2) {
            return new WriteCellData("女");
        } else {
            return new WriteCellData("状态异常");
        }
    }
}

工具类:

复制代码
package cn.ejar.cnos.management.system.api.util.excel;


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.converters.longconverter.LongStringConverter;
import com.alibaba.excel.util.DateUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;

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

/**
 * Excel工具类
 *
 */
public class ExcelUtils {

    /**
     * Excel导出
     *
     * @param response      response
     * @param fileName      文件名
     * @param sheetName     sheetName
     * @param list          数据List
     * @param pojoClass     对象Class
     */
    public static void exportExcel(HttpServletResponse response, String fileName, String sheetName, List<?> list,
                                   Class<?> pojoClass) throws IOException {
        if(StringUtils.isBlank(fileName)){
            //当前日期
            fileName = DateUtils.format(new Date());
        }

        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("UTF-8");
        fileName = URLEncoder.encode(fileName, "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" +  fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), pojoClass).registerConverter(new LongStringConverter()).sheet(sheetName).doWrite(list);
    }

    /**
     * Excel导出,先sourceList转换成List<targetClass>,再导出
     *
     * @param response      response
     * @param fileName      文件名
     * @param sheetName     sheetName
     * @param sourceList    原数据List
     * @param targetClass   目标对象Class
     */
    public static void exportExcelToTarget(HttpServletResponse response, String fileName, String sheetName, List<?> sourceList,
                                           Class<?> targetClass) throws Exception {
        List targetList = new ArrayList<>(sourceList.size());
        for(Object source : sourceList){
            Object target = targetClass.newInstance();
            BeanUtils.copyProperties(source, target);
            targetList.add(target);
        }

        exportExcel(response, fileName, sheetName, targetList, targetClass);
    }
}

导出方法:

复制代码
	public void export( HttpServletResponse response) throws Exception {
		


		List<UserMeetingDTO> list = new arrayList();

		ExcelUtils.exportExcelToTarget(response, "报名统计", "报名统计", list, UserMeetingVO.class);
	}

导出结果:

有任何不懂的地方可以评论区或者私信我,每天都会看博客.

相关推荐
m***567230 分钟前
在Nginx上配置并开启WebDAV服务的完整指南
java·运维·nginx
蓝眸少年CY30 分钟前
Python科学计算 Numpy库
开发语言·python·numpy
困惑阿三31 分钟前
深入理解 JavaScript 中的(Promise.race)
开发语言·前端·javascript·ecmascript·reactjs
我命由我1234533 分钟前
微信小程序 bind:tap 与 bindtap 的区别
开发语言·前端·javascript·微信小程序·小程序·前端框架·js
Mr.朱鹏37 分钟前
RocketMQ可视化监控与管理
java·spring boot·spring·spring cloud·maven·intellij-idea·rocketmq
带刺的坐椅40 分钟前
Solon AI 开发学习9 - chat - 聊天会话(对话)的记忆与持久化
java·ai·llm·openai·solon·mcp
曹牧40 分钟前
Oracle中ROW_NUMBER() OVER()
java·数据库·sql
客梦42 分钟前
数据结构-哈希表
java·数据结构·笔记
Yolo566Q43 分钟前
基于ArcGIS、InVEST与RUSLE水土流失模拟及分析
开发语言·python
草原印象1 小时前
Spring SpringMVC Mybatis框架整合实战
java·spring·mybatis·spring mvc