1、安装 xlsx 库:
npm install xlsx
2、在你的组件中引入 xlsx 库:
import * as XLSX from 'xlsx';
3、添加导出按钮到你的模板:
- <el-button type="primary" @click="exportToExcel">导出Excelel-button>
4、exportToExcel函数
- // 导出 Excel
- const exportToExcel = () => {
- // 构建工作簿
- const wb = XLSX.utils.book_new();
- const ws = XLSX.utils.json_to_sheet(tableData.value);
-
- // 将工作表添加到工作簿
- XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
-
- // 将工作簿转为 ArrayBuffer
- const arrayBuffer = XLSX.write(wb, { bookType: 'xlsx', type: 'array' });
-
- // 创建 Blob
- const blob = new Blob([arrayBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
-
- // 创建下载链接
- const url = URL.createObjectURL(blob);
- const a = document.createElement('a');
- a.href = url;
- a.download = 'exported_data.xlsx';
-
- // 模拟点击下载链接
- document.body.appendChild(a);
- a.click();
- document.body.removeChild(a);
- URL.revokeObjectURL(url);
- };