使用 Axios Blob 导出 Excel 文件的前端实现
在现代 Web 开发中,将数据导出为 Excel 文件是一项常见需求。通过后端发送 Excel 文件,前端接收并保存,可以有效提升用户体验。本文将介绍如何使用 Axios 和 Blob 结合,将 Excel 文件导出到前端。
1. 安装 Axios
首先,我们需要确保在项目中安装了 Axios。如果你还没有安装,可以使用 npm 或 yarn 进行安装:
npm install axios
2. 后端准备
假设我们的后端使用 Node.js 和 Express,以下是一个简单的示例,生成 Excel 文件并返回:
const express = require('express');
const ExcelJS = require('exceljs');
const app = express();
app.get('/download-excel', async (req, res) => {
const workbook = new ExcelJS.Workbook();
const worksheet = workbook.addWorksheet('数据');
// 添加表头
worksheet.columns = [
{ header: '姓名', key: 'name' },
{ header: '年龄', key: 'age' },
{ header: '性别', key: 'gender' },
];
// 添加数据
worksheet.addRow({ name: '小明', age: 22, gender: '男' });
worksheet.addRow({ name: '小红', age: 20, gender: '女' });
// 设置响应类型为 Excel
res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
res.setHeader('Content-Disposition', 'attachment; filename="data.xlsx"');
return workbook.xlsx.write(res).then(() => {
res.end();
});
});
app.listen(3000, () => {
console.log('服务启动在 http://localhost:3000');
});
上面的代码实现了一个简单的服务,能够生成一个包含姓名、年龄和性别的 Excel 文件。
3. 前端实现
在 Vue 或 React 项目中,可以通过 Axios 获取 Excel 文件并使用 Blob 对象处理文件下载。
Vue 示例
以下是一个简单的 Vue 组件示例,展示如何下载 Excel 文件:
<template>
<button @click="downloadExcel">下载 Excel</button>
</template>
<script>
import axios from 'axios';
export default {
methods: {
async downloadExcel() {
try {
const response = await axios.get('http://localhost:3000/download-excel', {
responseType: 'blob',
});
const blob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.setAttribute('download', 'data.xlsx');
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
} catch (error) {
console.error('下载失败', error);
}
}
}
}
</script>
React 示例
以下是一个简单的 React 组件示例,展示相同的功能:
import React from 'react';
import axios from 'axios';
const DownloadExcel = () => {
const downloadExcel = async () => {
try {
const response = await axios.get('http://localhost:3000/download-excel', {
responseType: 'blob',
});
const blob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.setAttribute('download', 'data.xlsx');
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
} catch (error) {
console.error('下载失败', error);
}
};
return <button onClick={downloadExcel}>下载 Excel</button>;
};
export default DownloadExcel;
4. 交互过程序列图
我们可以使用序列图来表示用户与应用的交互过程:
sequenceDiagram
participant User
participant Frontend
participant Backend
User->>Frontend: 点击下载 Excel 按钮
Frontend->>Backend: 发送 GET 请求
Backend-->>Frontend: 返回 Excel Blob
Frontend->>User: 下载 Excel 文件
结论
通过使用 Axios 和 Blob,我们可以方便地实现 Excel 文件的前端下载。借助 ExcelJS 生成 Excel 文件,可以更灵活地定制数据格式。掌握这样的技术,可以提升你在前端开发中的实际应用能力。希望这篇文章能对你的开发之旅有所帮助!