vue实现批量导出
Vue 实现批量导出的方法
使用第三方库(如 xlsx 和 file-saver)
安装依赖库:
npm install xlsx file-saver --save
创建导出逻辑:
import XLSX from 'xlsx';
import { saveAs } from 'file-saver';
export default {
methods: {
exportToExcel(data, fileName) {
const worksheet = XLSX.utils.json_to_sheet(data);
const workbook = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
const blob = new Blob([excelBuffer], { type: 'application/octet-stream' });
saveAs(blob, `${fileName}.xlsx`);
},
handleBatchExport() {
const dataList = [...]; // 需要导出的数据数组
dataList.forEach((data, index) => {
this.exportToExcel(data, `export_${index + 1}`);
});
}
}
}
使用纯前端实现(无依赖)
创建 CSV 导出方法:
export default {
methods: {
exportToCSV(data, fileName) {
const headers = Object.keys(data[0]).join(',');
const rows = data.map(item => Object.values(item).join(','));
const csvContent = [headers, ...rows].join('\n');
const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.setAttribute('download', `${fileName}.csv`);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
},
batchExportCSV(dataList) {
dataList.forEach((data, index) => {
this.exportToCSV(data, `export_${index + 1}`);
});
}
}
}
结合后端 API 实现
前端请求批量导出:
export default {
methods: {
async batchExportFromAPI(ids) {
try {
const responses = await Promise.all(
ids.map(id => axios.get(`/api/export/${id}`, { responseType: 'blob' }))
);
responses.forEach((res, index) => {
const blob = new Blob([res.data]);
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.setAttribute('download', `export_${ids[index]}.xlsx`);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
});
} catch (error) {
console.error('导出失败:', error);
}
}
}
}
优化用户体验
添加进度提示:
export default {
data() {
return {
exportProgress: 0,
totalExports: 0
};
},
methods: {
async batchExportWithProgress(dataList) {
this.totalExports = dataList.length;
this.exportProgress = 0;
for (const [index, data] of dataList.entries()) {
await this.exportToExcel(data, `export_${index + 1}`);
this.exportProgress = Math.round(((index + 1) / this.totalExports) * 100);
}
}
}
}
模板中添加进度显示:
<template>
<div>
<button @click="batchExportWithProgress(dataList)">批量导出</button>
<div v-if="exportProgress > 0">
导出进度: {{ exportProgress }}%
</div>
</div>
</template>






