一 . 安装依赖
npm install xlsx file-saver --save
二. 引入
import FileSaver from 'file-saver'
import XLSX from 'xlsx'
三. 下载
3.1 单表格下载
<template>
<div>
<el-button type="primary" @click="downExcel">下载至Excel</el-button>
<el-table id="example" :data="listData">
<el-table-column label="姓名" prop="name"></el-table-column>
<el-table-column label="性别" prop="sex"></el-table-column>
<el-table-column label="年龄" prop="age"></el-table-column>
</el-table>
</div>
</template>
<script>
import FileSaver from 'file-saver'
import XLSX from 'xlsx'
export default {
data() {
return {
listData: [{
name:'aa',
sex:'男',
age:10
},{
name:'bb',
sex:'女',
age:12
},{
name:'cc',
sex:'男',
age:15
}]
};
},
methods: {
//下载数据至Excel
downExcel() {
let et = XLSX.utils.table_to_book(document.getElementById("example")); //此处传入table的DOM节点
let etout = XLSX.write(et, {
bookType: "xlsx",
bookSST: true,
type: "array"
});
try {
FileSaver.saveAs(
new Blob([etout], {
type: "application/octet-stream"
}),
`人员信息.xlsx`
); //导出的文件名
} catch (e) {
console.log(e, etout);
}
return etout;
}
}
};
</script>
<style scoped>
</style>
3.2 多表格下载
<template>
<div>
<el-button type="primary" @click="downExcel">下载至Excel</el-button>
<el-table id="Table1" :data="listData">
<el-table-column label="姓名" prop="name"></el-table-column>
<el-table-column label="性别" prop="sex"></el-table-column>
<el-table-column label="年龄" prop="age"></el-table-column>
</el-table>
<el-table id="Table2" :data="listData1">
<el-table-column label="姓名" prop="name"></el-table-column>
<el-table-column label="科目" prop="subject"></el-table-column>
<el-table-column label="成绩" prop="achievement"></el-table-column>
</el-table>
</div>
</template>
<script>
import FileSaver from 'file-saver'
import XLSX from 'xlsx'
export default {
data() {
return {
listData: [{
name:'aa',
sex:'男',
age:10
},{
name:'bb',
sex:'女',
age:12
},{
name:'cc',
sex:'男',
age:15
}],
listData1: [{
name:'aa',
subject:'语文',
achievement:98
},{
name:'aa',
subject:'数学',
achievement:95
},{
name:'aa',
subject:'英语',
achievement:96
}],
};
},
methods: {
//下载数据至Excel
downExcel() {
var workbook = XLSX.utils.book_new();
/* convert table 'table1' to worksheet named "Sheet1" */
var ws1 = XLSX.utils.table_to_sheet(document.getElementById('Table1'));
XLSX.utils.book_append_sheet(workbook, ws1, "sheet1");
/* convert table 'table2' to worksheet named "Sheet2" */
var ws2 = XLSX.utils.table_to_sheet(document.getElementById('Table2'));
XLSX.utils.book_append_sheet(workbook, ws2, "sheet2");
/* get binary string as output */
var wbOut = XLSX.write(workbook, {
bookType: "xlsx",
bookSST: true,
type: "array"
});
try {
FileSaver.saveAs(
new Blob([wbOut], { type: "application/octet-stream" }),
"信息.xlsx"
);
} catch (e) {
if (typeof console !== "undefined") console.log(e, wbOut);
}
return wbout;
}
}
};
</script>
<style scoped>
</style>