0
点赞
收藏
分享

微信扫一扫

亚马逊云科技数据工程师考试官方免费课程上线啦

阎小妍 2天前 阅读 2

使用 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);
	}

导出结果:

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

举报

相关推荐

0 条评论