导入导出之使用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);
	}

导出结果:

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

相关推荐
zaim139 分钟前
计算机的错误计算(一百一十四)
java·c++·python·rust·go·c·多项式
学习使我变快乐43 分钟前
C++:const成员
开发语言·c++
500了2 小时前
Kotlin基本知识
android·开发语言·kotlin
hong_zc2 小时前
算法【Java】—— 二叉树的深搜
java·算法
bin91533 小时前
【EXCEL数据处理】000010 案列 EXCEL文本型和常规型转换。使用的软件是微软的Excel操作的。处理数据的目的是让数据更直观的显示出来,方便查看。
大数据·数据库·信息可视化·数据挖掘·数据分析·excel·数据可视化
进击的女IT3 小时前
SpringBoot上传图片实现本地存储以及实现直接上传阿里云OSS
java·spring boot·后端
Miqiuha3 小时前
lock_guard和unique_lock学习总结
java·数据库·学习
一 乐4 小时前
学籍管理平台|在线学籍管理平台系统|基于Springboot+VUE的在线学籍管理平台系统设计与实现(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端·学习
不知所云,4 小时前
qt cmake自定义资源目录,手动加载资源(图片, qss文件)
开发语言·qt
数云界4 小时前
如何在 DAX 中计算多个周期的移动平均线
java·服务器·前端