vue报表导出实现
Vue 报表导出实现方法
使用 xlsx 库导出 Excel
安装 xlsx 库:
npm install xlsx
在 Vue 组件中引入并使用:
import * as XLSX from 'xlsx';
export default {
methods: {
exportToExcel() {
const data = [
['姓名', '年龄', '城市'],
['张三', 25, '北京'],
['李四', 30, '上海']
];
const ws = XLSX.utils.aoa_to_sheet(data);
const wb = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
XLSX.writeFile(wb, '报表.xlsx');
}
}
}
使用 html2canvas 和 jsPDF 导出 PDF
安装依赖:
npm install html2canvas jspdf
实现代码:
import html2canvas from 'html2canvas';
import jsPDF from 'jspdf';
export default {
methods: {
exportToPDF() {
const element = document.getElementById('report-content');
html2canvas(element).then(canvas => {
const imgData = canvas.toDataURL('image/png');
const pdf = new jsPDF('p', 'mm', 'a4');
const imgWidth = 210;
const imgHeight = canvas.height * imgWidth / canvas.width;
pdf.addImage(imgData, 'PNG', 0, 0, imgWidth, imgHeight);
pdf.save('报表.pdf');
});
}
}
}
使用 vue-json-excel 插件
安装插件:
npm install vue-json-excel
全局注册:
import Vue from 'vue';
import JsonExcel from 'vue-json-excel';
Vue.component('downloadExcel', JsonExcel);
组件中使用:
<template>
<download-excel
:data="jsonData"
:fields="jsonFields"
name="报表.xls">
<button>导出 Excel</button>
</download-excel>
</template>
<script>
export default {
data() {
return {
jsonFields: {
'姓名': 'name',
'年龄': 'age',
'城市': 'city'
},
jsonData: [
{ name: '张三', age: 25, city: '北京' },
{ name: '李四', age: 30, city: '上海' }
]
}
}
}
</script>
使用 echarts 导出图表
如果报表包含 echarts 图表,可以这样导出:
exportChart() {
const chart = this.$refs.chart.getChart();
const imgUrl = chart.getDataURL({
type: 'png',
pixelRatio: 2,
backgroundColor: '#fff'
});
const link = document.createElement('a');
link.href = imgUrl;
link.download = '图表.png';
link.click();
}
服务端生成报表
对于复杂报表,建议后端生成:
exportReport() {
axios.get('/api/export-report', {
responseType: 'blob'
}).then(response => {
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', '报表.xlsx');
document.body.appendChild(link);
link.click();
});
}
注意事项
- 大数据量导出时考虑分页或流式处理
- 导出前显示加载状态提升用户体验
- 移动端注意导出文件兼容性问题
- 考虑添加权限控制,避免未授权导出
以上方法可根据实际需求组合使用,实现各种复杂的报表导出功能。







