当前位置: 首页 > news >正文

使用Spring Boot和EasyExcel导出Excel文件,并在前端使用Axios进行请求

在现代企业应用中,Excel文件的导出是一项常见且重要的功能。Spring Boot作为Java开发中的热门框架,结合EasyExcel这样的高效库,能够轻松实现Excel的导出功能。而在前端,使用Axios进行HTTP请求,可以方便地与后端进行数据交互,实现文件的下载。本文将详细介绍如何在Spring Boot中使用EasyExcel导出Excel文件,并在前端通过Axios进行请求。


一、引言

Excel文件导出功能在企业应用中广泛应用于数据报告、统计分析等场景。传统的POI库虽然功能强大,但在处理大数据量时效率较低。EasyExcel作为阿里巴巴开源的一款高性能Excel处理库,能够显著提升导出效率。而Spring Boot提供了简洁的配置和开发体验,结合EasyExcel,可以快速实现高效稳定的Excel导出功能。前端使用Axios进行HTTP请求,能够轻松实现文件的下载,提升用户体验。


二、环境准备

在开始开发之前,请确保以下环境和工具已经准备就绪:

  • 开发工具:IntelliJ IDEA或Eclipse
  • Java开发环境:JDK 8及以上
  • Spring Boot:版本2.5.0及以上
  • EasyExcel:版本2.2.10及以上
  • 前端框架:Vue.js或其他JavaScript框架
  • Axios:用于发送HTTP请求

此外,建议读者具备基本的Spring Boot和前端开发经验,以便更好地理解后续内容。


三、后端实现

1. 导入依赖

在Spring Boot项目中,首先需要在pom.xml文件中添加EasyExcel和相关依赖:

<dependencies><!-- Spring Boot Starter Web --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!-- EasyExcel --><dependency><groupId>com.alibaba</groupId><artifactId>easyexcel</artifactId><version>2.2.10</version></dependency><!-- 其他依赖 --><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency>
</dependencies>

2. 配置类

创建一个配置类,确保EasyExcel的相关组件被正确加载:

import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.BaseRowModel;
import com.alibaba.excel.util.FileUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;@Configuration
public class ExcelConfig {@Beanpublic ExcelWriter excelWriter() {return new ExcelWriter();}@Beanpublic FileUtils fileUtils() {return new FileUtils();}
}

3. 服务接口

编写一个服务接口,定义导出Excel的方法:

import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.BaseRowModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.io.IOException;
import java.io.OutputStream;
import java.util.List;@Service
public class ExcelExportService {@Autowiredprivate ExcelWriter excelWriter;public void exportExcel(OutputStream outputStream, List<? extends BaseRowModel> data) throws IOException {excelWriter.write(data, outputStream);}
}

4. 控制层

创建一个RESTful API,处理前端的导出请求,并调用服务层的方法生成Excel文件:

import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.BaseRowModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import java.io.IOException;
import java.io.OutputStream;
import java.util.List;@RestController
@RequestMapping("/api/excel")
public class ExcelExportController {@Autowiredprivate ExcelExportService excelExportService;@GetMapping("/export")public ResponseEntity<?> exportExcel() {try {// 获取数据List<MyDataModel> data = getData();// 响应流OutputStream outputStream = response.getOutputStream();// 导出ExcelexcelExportService.exportExcel(outputStream, data);return ResponseEntity.status(HttpStatus.OK).build();} catch (IOException e) {e.printStackTrace();return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();}}private List<MyDataModel> getData() {// 从数据库或其他数据源获取数据return data;}
}

四、前端实现

1. 引入Axios

在前端项目中,安装并引入Axios:

npm install axios

然后在JavaScript文件中引入:

import axios from 'axios';

2. 组件开发

创建一个按钮或其他交互元素,触发导出功能:

<template><button @click="exportExcel">导出Excel</button>
</template><script>
import axios from 'axios';export default {methods: {exportExcel() {axios.get('/api/excel/export', {responseType: 'blob'}).then(response => {const blob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });const url = window.URL.createObjectURL(blob);const a = document.createElement('a');a.href = url;a.download = 'data.xlsx';a.click();window.URL.revokeObjectURL(url);}).catch(error => {console.error('导出失败:', error);});}}
}
</script>

3. 处理响应

前端接收到后端返回的Excel文件流后,使用Blob和FileSaver.js将其下载到本地:

axios.get('/api/excel/export', {responseType: 'blob'
}).then(response => {const blob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });const url = window.URL.createObjectURL(blob);const a = document.createElement('a');a.href = url;a.download = 'data.xlsx';a.click();window.URL.revokeObjectURL(url);
}).catch(error => {console.error('导出失败:', error);
});

五、注意事项

  1. 跨域问题

    • 确保前端和后端的CORS配置正确,允许前端域访问后端API。
  2. 性能优化

    • 处理大数据量时,可以分页导出或使用流式处理,避免内存溢出。
  3. 异常处理

    • 在前端和后端分别添加异常处理逻辑,提升用户体验和系统稳定性。

六、总结

通过本文的介绍,读者可以掌握如何在Spring Boot中使用EasyExcel实现Excel文件的导出功能,并在前端使用Axios进行请求,完成文件的下载。EasyExcel的高性能和Spring Boot的简洁配置,使得这一过程变得高效且易于维护。希望本文能够帮助读者在实际项目中快速实现Excel导出功能,并提升整体应用的用户体验。


七、附录

完整代码示例

后端代码:

// ExcelConfig.java
@Configuration
public class ExcelConfig {@Beanpublic ExcelWriter excelWriter() {return new ExcelWriter();}@Beanpublic FileUtils fileUtils() {return new FileUtils();}
}// ExcelExportService.java
@Service
public class ExcelExportService {@Autowiredprivate ExcelWriter excelWriter;public void exportExcel(OutputStream outputStream, List<? extends BaseRowModel> data) throws IOException {excelWriter.write(data, outputStream);}
}// ExcelExportController.java
@RestController
@RequestMapping("/api/excel")
public class ExcelExportController {@Autowiredprivate ExcelExportService excelExportService;@GetMapping("/export")public ResponseEntity<?> exportExcel() {try {List<MyDataModel> data = getData();OutputStream outputStream = response.getOutputStream();excelExportService.exportExcel(outputStream, data);return ResponseEntity.status(HttpStatus.OK).build();} catch (IOException e) {e.printStackTrace();return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();}}private List<MyDataModel> getData() {// 从数据库或其他数据源获取数据return data;}
}

前端代码:

// 导出Excel的方法
exportExcel() {axios.get('/api/excel/export', {responseType: 'blob'}).then(response => {const blob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });const url = window.URL.createObjectURL(blob);const a = document.createElement('a');a.href = url;a.download = 'data.xlsx';a.click();window.URL.revokeObjectURL(url);}).catch(error => {console.error('导出失败:', error);});
}

相关资源

  • EasyExcel官方文档:https://github.com/alibaba/easyexcel
  • Spring Boot官方文档:https://spring.io/guides
  • Axios官方文档:https://axios-http.com/

通过以上资源,读者可以进一步学习和探索相关技术,提升自己的开发能力。

http://www.xdnf.cn/news/1373455.html

相关文章:

  • 部署网页在服务器(公网)上笔记 infinityfree 写一个找工作单html文件的网站
  • 趣味学Rust基础篇(变量与可变性)
  • 从传统到创新:用报表插件重塑数据分析平台
  • 基于Spark的白酒行业数据分析与可视化系统的设计与实现
  • 【服务器】用X99主板组装服务器注意事项
  • 【开题答辩全过程】以 微信小程序的医院挂号预约系统为例,包含答辩的问题和答案
  • 在Excel和WPS表格中通过查找替换对单元格批量强制换行
  • 实现基于数据库 flag 状态的消息消费控制
  • PMP项目管理知识点-⑭【①-⑬流程总结】→图片直观表示
  • 让ai写一个类github首页
  • 从文本到二进制:HTTP/2不止于性能,更是对HTTP/1核心语义的传承与革新
  • 深度学习11 Deep Reinforcement Learning
  • 深度学习12 Reinforcement Learning with Human Feedback
  • 如何在阿里云百炼中使用钉钉MCP
  • 深度学习——激活函数
  • 【stm32简单外设篇】-4×4 薄膜键盘
  • 区块链技术探索与应用:从密码学奇迹到产业变革引擎
  • 【PS实战】制作hello标志设计:从选区到色彩填充的流程(大学作业)
  • 开发electron时候Chromium 报 Not allowed to load local resource → 空白页。
  • 【分布式技术】Kafka 数据积压全面解析:原因、诊断与解决方案
  • 基于muduo库的图床云共享存储项目(一)
  • More Effective C++ 条款10:在构造函数中防止资源泄漏
  • Tomcat的VM options
  • 广告推荐模型3:域感知因子分解机(Field-aware Factorization Machine, FFM)
  • 变压器副边电流计算
  • ARP地址解析协议
  • 嵌入式C语言进阶:结构体封装函数的艺术与实践
  • Java 集合笔记
  • 宝石组合(蓝桥杯)
  • 2025最新的软件测试热点面试题(答案+解析)