EasyExcel实现Excel文件导入导出

介绍

easyexcel 是阿里巴巴开源的一款 Java 解析 Excel 工具。

easyexcel Github 项目仓库地址:https://github.com/alibaba/easyexcel

easyexcel 项目依赖于 Apache POI工具库,是 POI 的抽象封装,它简化了对 excel 文件的操作,可以提高代码开发效率。

使用

Maven 项目 pom 文件中引入依赖:

 <dependency>
     <groupId>com.alibaba</groupId>
     <artifactId>easyexcel</artifactId>
     <version>2.0.0</version>
 </dependency>

导入导出

这里以导入导出学生信息为例,首先定义一个学生信息的excel实体类:

import com.alibaba.excel.annotation.ExcelProperty;
import lombok.Data;

@Data
public class StudentExcelDto {
    @ExcelProperty("学号")
    private String studentNumber;
    @ExcelProperty("姓名")
    private String name;
    @ExcelProperty("年龄")
    private Integer age;
    @ExcelProperty("年级")
    private String grade;
    @ExcelProperty("班级")
    private String classroom;
}

导出excel:

/**
 * 导出学生信息excel
 *
 * @param response http响应
 */
public void exportStudentInfoExcel(HttpServletResponse response) throws IOException {
    // ----- 获取导出数据 -----
    List<StudentExcelDto> studentExcelInfo = getStudentExcelInfo();

    //----- 写入excel文件
    String exportFileName = "StudentExportData.xlsx";
    response.setCharacterEncoding("UTF-8");
    response.setContentType("application/vnd.ms-excel");
    response.addHeader("Content-Disposition", "attachment;filename=" + exportFileName);
    EasyExcel.write(response.getOutputStream(), StudentExcelDto.class)
            .sheet("学生信息")
            //自动列宽
            .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
            .doWrite(studentExcelInfo);
}

private List<StudentExcelDto> getStudentExcelInfo() {
    List<StudentExcelDto> dataList = new ArrayList<>();
    for (int i = 1; i < 10; i++) {
        StudentExcelDto studentExcelDto = new StudentExcelDto();
        studentExcelDto.setStudentNumber(String.valueOf(i));
        studentExcelDto.setName("学生" + i);
        studentExcelDto.setAge(7 + i);
        studentExcelDto.setGrade(i + "年级");
        studentExcelDto.setClassroom("三年二班");
        dataList.add(studentExcelDto);
    }
    return dataList;
}

在 controller 层使用:

@Autowired
private EasyexcelService easyexcelService;

@GetMapping(value = "/export")
public void exportStudentInfoExcel(HttpServletResponse response) throws IOException {
    easyexcelService.exportStudentInfoExcel(response);
}

导出效果如下:

示例

导入excel

使用 easyexcel 读取上传的 excel 文件,需要先定义一个继承了 com.alibaba.excel.event.AnalysisEventListener 的数据监听器。

这里定义一个纯粹用于读取数据的监听器:

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * 数据监听器
 *
 * @param <T>
 */
@Slf4j
public class DataEasyExcelListener<T> extends AnalysisEventListener<T> {
    private List<T> list = new ArrayList<>();

    @Override
    public void invoke(T data, AnalysisContext context) {
        log.info("解析到一条数据:{}", data);
        list.add(data);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        log.info("所有数据解析完成!");
    }

    public List<T> getData() {
        return list;
    }

}

导入学生信息:

/**
 * 导入学生信息
 *
 * @param file 学生信息excel
 */
public void importStudentInfoExcel(MultipartFile file) throws IOException {
    // ------ 这里省略excel文件校验 -----

    // ----- 读取excel数据 -----
    DataEasyExcelListener<StudentExcelDto> listener = new DataEasyExcelListener<>();
    InputStream inputStream = file.getInputStream();
    EasyExcel.read(inputStream, StudentExcelDto.class, listener).sheet(0).doRead();
    List<StudentExcelDto> data = listener.getData();
    System.out.println("导入的学生信息:");
    System.out.println(data);
	
	// ----- 这里省略数据存储 -----
}

在 controller 层使用:

@RequestMapping(value = "/import", method = {RequestMethod.GET, RequestMethod.POST})
public String importStudentInfoExcel(@RequestParam("file") MultipartFile file) throws IOException {
    easyexcelService.importStudentInfoExcel(file);
    return "success";
}

使用 postman 测试:

示例
读取成功

示例

资料

  • 3
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值