FastExcel使用详解

文章目录

FastExcel使用详解

一、引言

FastExcel 是由原 EasyExcel 作者维护的高性能 Excel 处理库,专注于解决大规模数据读写时的内存溢出问题。它兼容 EasyExcel 的 API,同时新增了流式处理、读取指定行数、Excel 转 PDF 等功能,适用于企业级数据导入导出、报表生成等场景。本文将从环境配置、核心功能到实际应用示例,详细解析 FastExcel 的使用方法。


二、环境准备与依赖引入

1、Maven 依赖引入

pom.xml 中添加以下依赖:

xml 复制代码
<dependency>
    <groupId>cn.idev.excel</groupId>
    <artifactId>fastexcel</artifactId>
    <version>1.1.0</version>
</dependency>

2、实体类定义

通过 @ExcelProperty 注解实现 Excel 列与 Java 对象的映射:

java 复制代码
@Data
public class User {
    @ExcelProperty("编号")
    private Integer id;
    @ExcelProperty("姓名")
    private String name;
    @ExcelProperty("年龄")
    private Integer age;
}

说明 :使用 @Data(Lombok 注解)自动生成 Getter/Setter,简化代码。


三、核心操作:读写 Excel

1、读取 Excel

FastExcel 通过 事件监听器 实现流式读取,避免内存溢出。

1.1 自定义监听器
java 复制代码
public class UserReadListener implements ReadListener<User> {
    private List<User> dataList = new ArrayList<>();

    @Override
    public void invoke(User user, AnalysisContext context) {
        dataList.add(user); // 逐行处理数据
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        System.out.println("共读取 " + dataList.size() + " 条数据");
    }
}
1.2 读取文件
java 复制代码
String fileName = "users.xlsx";
FastExcel.read(fileName, User.class, new UserReadListener()).sheet().doRead();

2、写入 Excel

2.1 简单写入
java 复制代码
List<User> users = new ArrayList<>();
users.add(new User(1, "张三", 25));
users.add(new User(2, "李四", 30));

FastExcel.write("output.xlsx")
    .sheet("用户列表")
    .head(User.class)
    .doWrite(users);
2.2 模板写入

若需复杂格式,可基于模板填充数据:

java 复制代码
try (ExcelWriter writer = FastExcel.write("output.xlsx").withTemplate("template.xlsx").build()) {
    FillConfig fillConfig = FillConfig.builder().forceNewRow(true).build();
    writer.fill(users, fillConfig, writerSheet);
}

四、Spring Boot 集成示例

1、文件上传(导入)

java 复制代码
@PostMapping("/upload")
public ResponseEntity<String> upload(@RequestParam("file") MultipartFile file) {
    try {
        UserReadListener listener = new UserReadListener();
        FastExcel.read(file.getInputStream(), User.class, listener).sheet().doRead();
        return ResponseEntity.ok("导入成功,数据量:" + listener.getDataList().size());
    } catch (IOException e) {
        return ResponseEntity.status(500).body("导入失败");
    }
}

2、文件下载(导出)

java 复制代码
@GetMapping("/download")
public void download(HttpServletResponse response) throws IOException {
    response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
    response.setHeader("Content-Disposition", "attachment;filename=users.xlsx");
    
    List<User> users = userService.listAll(); // 假设从数据库获取数据
    FastExcel.write(response.getOutputStream(), User.class)
        .sheet("用户数据")
        .doWrite(users);
}

五、总结

FastExcel 凭借其 高性能流式处理简洁的 API,成为处理大规模 Excel 数据的首选工具。相比传统库(如 Apache POI),其内存占用更低,特别适合百万级数据的导入导出。

适用场景

  • 企业级数据报表生成
  • 批量数据导入数据库
  • 高并发环境下的 Excel 处理

版权声明:本博客内容为原创,转载请保留原文链接及作者信息。

参考文章

相关推荐
寻星探路42 分钟前
【深度长文】万字攻克网络原理:从 HTTP 报文解构到 HTTPS 终极加密逻辑
java·开发语言·网络·python·http·ai·https
lly2024062 小时前
Bootstrap 警告框
开发语言
2601_949146533 小时前
C语言语音通知接口接入教程:如何使用C语言直接调用语音预警API
c语言·开发语言
曹牧3 小时前
Spring Boot:如何测试Java Controller中的POST请求?
java·开发语言
KYGALYX3 小时前
服务异步通信
开发语言·后端·微服务·ruby
zmzb01033 小时前
C++课后习题训练记录Day98
开发语言·c++
猫头虎4 小时前
如何排查并解决项目启动时报错Error encountered while processing: java.io.IOException: closed 的问题
java·开发语言·jvm·spring boot·python·开源·maven
YUJIANYUE4 小时前
PHP纹路验证码
开发语言·php
仟濹5 小时前
【Java基础】多态 | 打卡day2
java·开发语言
孞㐑¥5 小时前
算法——BFS
开发语言·c++·经验分享·笔记·算法