vue springboot项目导出excel
时间: 2024-12-30 18:33:16 浏览: 29
实现 Vue 和 Spring Boot 项目的 Excel 文件导出
后端实现 (Spring Boot)
为了高效处理大量数据并减少内存占用,推荐采用阿里巴巴开源的 EasyExcel 库来实现出口功能[^2]。
在 pom.xml
中引入所需依赖:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>3.0.5</version>
</dependency>
<!-- 防止 slf4j 的依赖冲突 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.2</version>
</dependency>
创建用于导出的数据模型类,并添加必要的注解以便于映射到 Excel 表格列上。例如,在 Notice.java
类中定义字段及其对应的表头名称。
编写控制器方法以响应前端请求并返回 Excel 流给客户端下载:
@RestController
@RequestMapping("/notice")
public class NoticeController {
@GetMapping("/export-excel")
public void export(HttpServletResponse response) throws IOException {
// 设置HTTP响应头部信息
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");
String fileName = URLEncoder.encode("通知公告", "UTF-8").replaceAll("\\+", "%20");
response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
List<Notice> notices = noticeService.findAll(); // 假设有一个服务层获取所有记录
try (
OutputStream out = response.getOutputStream();
) {
EasyExcel.write(out, Notice.class).sheet("Sheet1").doWrite(notices);
}
}
}
前端实现 (Vue.js)
对于前端部分,则是在页面按钮点击事件触发时向服务器发起 GET 请求,并设置合适的 HTTP 头部参数让浏览器识别这是一个文件下载操作[^3]。
修改 Notice.vue
组件中的模板和脚本如下所示:
<template>
<div>
<!-- ...其他HTML结构... -->
<el-form-item>
<button type="button" @click="handleExport">导出Excel</button>
</el-form-item>
</div>
</template>
<script>
import axios from 'axios';
export default {
name: 'Notice',
methods: {
handleExport() {
const url = '/api/notice/export-excel';
axios({
method: 'GET',
url,
responseType: 'blob', // 关键配置项,表示这是二进制流而非JSON对象
}).then((response) => {
const linkElement = document.createElement('a');
let blob = new Blob([response.data], {type : 'application/octet-stream'});
let urlToDownload = window.URL.createObjectURL(blob);
linkElement.setAttribute('href', urlToDownload );
linkElement.setAttribute('download', '通知公告.xlsx');
linkElement.style.display = 'none';
document.body.appendChild(linkElement);
linkElement.click();
linkElement.remove();
});
},
},
};
</script>
这样就完成了整个流程的设计与编码工作,当用户访问该页面并点击“导出Excel”按钮后即可获得由后台生成的通知公告列表形式的 Excel 文档。
阅读全文
相关推荐


















