EasyExcel在SpringBoot中的简单使用

简介

EasyExcel是一个基于Apache POI的Excel处理工具,它能够以简单的方式读写大型Excel文件,并且性能高效、内存占用低。在SpringBoot中集成EasyExcel可以极大地提高数据处理效率。以下是EasyExcel在SpringBoot中的简单使用教程。

步骤1:添加依赖

首先,在你的SpringBoot项目的pom.xml文件中添加EasyExcel的依赖。以下是依赖配置:

复制代码

xml

复制代码
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>easyexcel</artifactId>
    <version>3.1.1</version>
</dependency>
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.16.20</version>
</dependency>
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.11.0</version>
</dependency>

步骤2:准备数据模型

创建一个用于存储数据的实体类。例如,我们创建一个Order类来表示订单信息:

复制代码

java

复制代码
import lombok.Data;

@Data
public class Order {
    private Long id;
    private String productName;
    private Integer quantity;
    private BigDecimal price;
}

步骤3:实现Excel导出

定义一个名为ExcelExportUtil的工具类,其中包含一个静态方法writeToExcel。以下是导出Excel的示例代码:

复制代码

java

复制代码
import com.alibaba.excel.EasyExcel;
import java.io.File;
import java.io.FileOutputStream;
import java.util.List;

public class ExcelExportUtil {

    public static void writeToExcel(String filePath, List<Order> dataList) {
        // 定义文件输出位置
        FileOutputStream outputStream = new FileOutputStream(new File(filePath));
        // 写入Excel
        EasyExcel.write(outputStream, Order.class).sheet("订单信息").doWrite(dataList);
    }
}

步骤4:实现Excel导入

创建一个自定义读监听器OrderExcelListener,用于处理读取Excel时的数据:

复制代码

java

复制代码
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;

public class OrderExcelListener extends AnalysisEventListener<Order> {
    private List<Order> orderList = new ArrayList<>();

    @Override
    public void invoke(Order order, AnalysisContext analysisContext) {
        orderList.add(order);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        System.out.println("所有数据解析完成!");
    }

    public List<Order> getOrderList() {
        return orderList;
    }
}

步骤5:Controller层实现

Controller层,添加两个接口,一个用于导出Excel,另一个用于导入Excel:

复制代码

java

复制代码
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@RestController
public class ExcelController {

    @GetMapping("/export")
    public void export(HttpServletResponse response) throws IOException {
        // 设置响应头
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("订单信息", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

        // 模拟数据
        List<Order> orderList = new ArrayList<>();
        orderList.add(new Order(1L, "产品A", 10, new BigDecimal("100.00")));
        orderList.add(new Order(2L, "产品B", 20, new BigDecimal("200.00")));

        // 写入Excel
        EasyExcel.write(response.getOutputStream(), Order.class).sheet("订单信息").doWrite(orderList);
    }

    @PostMapping("/import")
    public String importExcel(@RequestParam("file") MultipartFile file) throws IOException {
        OrderExcelListener listener = new OrderExcelListener();
        EasyExcel.read(file.getInputStream(), Order.class, listener).sheet().doRead();
        List<Order> orderList = listener.getOrderList();
        // 这里可以将数据保存到数据库
        orderList.forEach(System.out::println);
        return "导入成功!";
    }
}

步骤6:测试

启动SpringBoot应用后,访问以下接口进行测试:

  • 导出:http://localhost:8080/export
  • 导入:通过Postman等工具,发送POST请求到http://localhost:8080/import,并上传一个包含订单信息的Excel文件。
相关推荐
计算机毕设匠心工作室11 小时前
【python大数据毕设实战】全球大学排名数据可视化分析系统、Hadoop、计算机毕业设计、包括数据爬取、数据分析、数据可视化、机器学习、实战教学
后端·python·mysql
千寻技术帮11 小时前
10413_基于Springboot的智慧养老院管理系统
spring boot·mysql·源码·安装·文档·ppt·养老院
霍夫曼12 小时前
UTC时间与本地时间转换问题
java·linux·服务器·前端·javascript
VX:Fegn089512 小时前
计算机毕业设计|基于Java人力资源管理系统(源码+数据库+文档)
java·开发语言·数据库·vue.js·spring boot·后端·课程设计
荔枝hu12 小时前
springboot和shiro组合引入SseEmitter的一些坑
java·spring boot·后端·sseeitter
老华带你飞12 小时前
健身房|基于springboot + vue健身房管理系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端
JIngJaneIL12 小时前
基于Java酒店预约系统(源码+数据库+文档)
java·开发语言·数据库·vue.js·spring boot
曹牧13 小时前
Java:List<Map<String, String>>转换为字符串
java·开发语言·windows
不会写DN13 小时前
存储管理在开发中有哪些应用?
前端·后端
Unstoppable2213 小时前
代码随想录算法训练营第 56 天 | 拓扑排序精讲、Dijkstra(朴素版)精讲
java·数据结构·算法·