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

导出结果:

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

  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 使用 EasyExcel 进行简单的表格导入导出功能,需要遵循以下步骤: 1. 安装 EasyExcel 使用 composer 安装 EasyExcel: ```bash composer require alibaba/easyexcel ``` 2. 导出 Excel ```php use AlibabaCloud\Client\AlibabaCloud; use AlibabaCloud\Client\Exception\ClientException; use AlibabaCloud\Client\Exception\ServerException; use AlibabaCloud\Ecs\Ecs; require_once __DIR__ . '/vendor/autoload.php'; use EasyExcel\Factory; // 定义导出数据 $data = [ ['姓名', '年龄', '性别'], ['张三', 20, '男'], ['李四', 25, '女'], ['王五', 30, '男'], ]; // 导出 Excel $exportFile = 'example.xlsx'; $exportPath = __DIR__ . '/' . $exportFile; $writer = Factory::createWriter('Xlsx'); $writer->openToFile($exportPath); $writer->addRows($data); $writer->close(); // 下载 Excel header('Content-type: application/vnd.ms-excel'); header('Content-Disposition: attachment; filename="' . $exportFile . '"'); readfile($exportPath); exit; ``` 3. 导入 Excel ```php use AlibabaCloud\Client\AlibabaCloud; use AlibabaCloud\Client\Exception\ClientException; use AlibabaCloud\Client\Exception\ServerException; use AlibabaCloud\Ecs\Ecs; require_once __DIR__ . '/vendor/autoload.php'; use EasyExcel\Factory; // 上传 Excel $importFile = $_FILES['file']['tmp_name']; // 导入 Excel $reader = Factory::createReader('Xlsx'); $reader->open($importFile); $data = $reader->getSheetData(); // 处理导入数据 array_shift($data); // 去掉表头 foreach ($data as $row) { $name = $row[0]; $age = $row[1]; $gender = $row[2]; // 处理数据... } ``` ### 回答2: EasyExcel是一个基于Java的开源框架,用于在Excel文件和Java对象之间进行简单、高效的导入导出操作。虽然问题中提到了"easyexcel php",但实际上EasyExcelJava库,并没有针对PHP的版本。 使用EasyExcel进行表格导入导出功能非常简单。首先,我们需要引入EasyExcel的依赖库,在项目中创建一个Excel导入导出的工具类。在这个工具类中,我们可以定义导入方法和导出方法。 对于导入功能,我们需要调用EasyExcel提供的方法,传入要导入Excel文件路径和导入后的数据处理器。数据处理器可以是实现了EasyExcel的ReadListener接口的类,这样我们可以在读取Excel数据完成后对数据进行自定义处理。 对于导出功能,我们需要将要导出的数据转化为相应格式,并调用EasyExcel提供的写方法,指定导出Excel文件路径和数据源即可。 总的来说,EasyExcel提供的API非常简洁易用,可以大大简化我们对Excel文件的导入导出操作。无论是简单的还是复杂的表格导入导出功能,都可以轻松实现。 ### 回答3: EasyExcel是一款基于Java语言开发的开源库,可以轻松实现Excel文件的读写操作。但是您的问题中提到的是PHP语言,由于EasyExcel是基于Java语言的库,所以无法直接在PHP中使用它。 不过,您可以通过其他方式来实现PHP中的表格导入导出功能。PHP提供了PHPExcel库,也是一个开源、易于使用Excel文件操作工具。它可以帮助我们在PHP中读取和写入Excel文件。 对于表格导出,您可以使用PHPExcel提供的相关类和方法来创建一个Excel文件,并通过设置单元格的值、样式和格式来填充数据。最后,使用PHPExcel提供的方法将文件保存为Excel格式。 对于表格导入,您可以使用PHPExcel提供的相关类和方法来打开一个已存在的Excel文件,并通过遍历和读取单元格的值来读取数据。可以根据文件中的格式和结构来逐行或逐列地读取数据,并进行后续的处理和操作。 总结来说,虽然没有使用EasyExcel库,但是通过使用PHPExcel库,我们同样可以在PHP中实现简单的表格导入导出功能。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值