首先需要2个JS文件,文章下方会给出,或者这俩个js搜一下应该都有的
页面2个按钮
data数据
JS如下
先点击模拟发送请求,再导出数据结果如下
实现多层结构导出,完整代码
<template>
<div>
<el-button type="primary" @click="getData">模拟发请求</el-button>
<el-button type="primary" @click="exportExcel">导出</el-button>
</div>
</template>
<script>
export default {
// name: "themeCfg",
data() {
return {
classList: [
{
className: "A班",
students: [
{
stuName: "xxx",
age: 38,
sex: "男"
},
{
stuName: " TTT",
age: 18,
sex: "女"
}
]
},
{
className: "B班",
students: [
{
stuName: " ZZZ",
age: 28,
sex: "男"
}
]
}
],
excelData: []
};
},
methods: {
getData() {
console.log("请求成功");
//拿到数组classList 根据你需要的数据处理,然后进行打印
//假设需要 每个班级的Name和其对应的学生信息 如 a班 xxx 28 男 || a班 TTT 18 女
this.classList.forEach(v => {
v["students"].forEach(j => {
// 定义一个空数组 接处理后的数据
this.excelData.push({
className: v["className"],
stuName: j["stuName"],
age: j["age"],
sex: j["sex"]
});
});
});
console.log(this.excelData);
},
exportExcel() {
//没有数据不打印
if (this.excelData.length === 0) {
return;
}
import("@/vendor/Export2Excel").then(excel => {
const tHeader = ["班级名称", "学生姓名", "年龄", "性别"];
const filterVal = ["className", "stuName", "age", "sex"];
const data = this.formatJson(filterVal, this.excelData);
excel.export_json_to_excel({
header: tHeader,
data,
filename: `某学校下班级学生数据_`
});
});
},
formatJson(filterVal, jsonData) {
return jsonData.map(v => filterVal.map(j => v[j]));
}
}
};
</script>
<style lang="less" scoped></style>
百度网盘提取文章开头说的2个js文件
链接: https://pan.baidu.com/s/16YwZbaYJt9NbVt8o5epOJQ 提取码: 1515
官网地址:https://www.npmjs.com/package/vue-json-excel
npm install vue-json-excel
在main.js中引入
import Vue from "vue";
import JsonExcel from "vue-json-excel";
Vue.component("JsonExcel", JsonExcel);
或者在页面按需引入,在components注册
import JsonExcel from "vue-json-excel";
components: {
JsonExcel
},
代码如下:
<JsonExcel :fields="json_fields" :data="jsonData" title="这里是导出的表头" name="用户信息.xlsx">
<el-button round type="primary">导出</el-button>
</JsonExcel>
data() {
return {
json_fields: {
姓名: "name", // 这里的表头字段可以自由指定
性别: "sex",
年龄: "age",
电话: "phone",
地址: "address"
},
jsonData: [
{ name: "张三", sex: "未知", age: 18, phone: 18888888, address: "华夏" }
]
}
}