我们在开发过程中会遇到下载excel文件的需求,特别是后台管理的项目。
首先我们先安装一下组件
npm install js-export-excel
or
yarn add js-export-excel
然后在需要使用的地方引入
const ExportJsonExcel = require("js-export-excel");
or
import ExportJsonExcel from "js-export-excel";
下面拿个案例
<template>
<div class="add">
<button @click="exportExcel">点击下载</button>
</div>
</template>
<script>
import ExportJsonExcel from "js-export-excel";
export default {
data(){
return{
selections:[
{'index':'0',"num": "100", "name": "苹果"},
{'index':'1',"num": "50", "name": "橘子"},
{'index':'2',"num": "330", "name": "香蕉"}
]
}
},
methods: {
//定义导出Excel表格事件
exportExcel: function () {
var data = this.selections;//选中的数据
let dataTable = [];
if (data && data.length > 0) {
for (let i in data) {
if (data[i]) {
let obj = {
索引: data[i].index,
数量: data[i].num,
商品: data[i].name
};
dataTable.push(obj);
}
}
this.exportToExcel(dataTable);
}
},
exportToExcel (dataTable) {
var option = {};
option.fileName = "商品数量";
option.datas = [
{
sheetData: dataTable,
sheetName: "sheet",
sheetFilter: [
"索引", // 要和上面定义的对应
"数量",
"商品"
],
sheetHeader: [
"索引",
"数量",
"商品"
]
}
];
var toExcel = new ExportJsonExcel(option);
toExcel.saveExcel();
}
}
}
</script>