前端下载后端的excel文件的两种方式
//当下载excel的时候,不让其操作
import { Loading } from 'element-ui'; //使用element的loading效果
let instance
const request = axios.create({
baseURL:'http://127.0.0.1:3000'
})
request.interceptors.request.use(function(config) {
instance = Loading.service({
// lock: true,
text: '数据加载中',
spinner: 'el-icon-loading',
background: 'rgba(254, 254, 254, 0.7)'
})
let token = localStorage.getItem('userToken')
if (token) {
config.headers.userToken = token
}
return config
})
request.interceptors.response.use(resp => {
instance.close() // 关闭
return resp
})
export const allUrl = (date1,date2) => {
return request({
url:`/dsc-toclass/exportall?date1=${date1}&date2=${date2}`,
method:'get',
responseType: "blob",
})
}
在你要下载的页面里‘
totalData() {
allUrl(this.dateArr[0], this.dateArr[1]).then( res => {
console.log(res,'154')
let url = window.URL.createObjectURL(new Blob([res.data]));
let link2 = document.createElement("a");
link2.style.display = "none";
link2.href = url;
link2.setAttribute("download", `${res.config.url.match(/(?<==)(\d|-)+/g)[0]}~${res.config.url.match(/(?<==)(\d|-)+/g)[1]}所有员工给班信息表.xlsx`);
document.body.appendChild(link2);
link2.click();
console.log(res,'161行的')
});
},
2.使用依赖包
npm install js-export-excel
or
yarn add js-export-excel
import ExportJsonExcel from “js-export-excel”;
<template>
<div class="box">
<div class="title">导出excel</div>
<el-button @click="exportExcel">导出</el-button>
</div>
</template>
<script>
import ExportJsonExcel from "js-export-excel";
export default {
data() {
return {
list: {
getList: [
{
id: "1",
province: "江西",
city: "赣州",
},
{
id: "2",
province: "广东",
city: "深圳",
},
{
id: "3",
province: "湖南",
city: "长沙",
},
{
id: "4",
province: "浙江",
city: "杭州",
},
{
id: "5",
province: "河南",
city: "洛阳",
},
{
id: "6",
province: "山东",
city: "青岛",
},
{
id: "7",
province: "安徽",
city: "烟台",
},
],
},
};
},
methods: {
exportExcel() {
console.log(123);
const dataList = this.list.getList;
let option = {}; // option代表的就是excel文件
let dataTable = []; // dataTable代表excel文件中的数据内容
if (dataList) {
for (let i in dataList) {
let obj = {
序号: dataList[i].id,
省份: dataList[i].province,
城市: dataList[i].city,
};
dataTable.push(obj); // 设置excel每列获取的数据源
}
}
option.filename = "省份城市表"; //excel文件名
//excel文件数据
option.datas = [
{
// excel文件的数据源
sheetData: dataTable,
// excel文件sheet的表名
sheetName: "sheet",
// excel文件表头名
sheetHeader: ["序号", "省份", "城市"],
// excel文件列名
sheetFilter: ["序号", "省份", "城市"],
},
];
// 创建ExportJsonExcel实例对象
let toExcel = new ExportJsonExcel(option);
// 调用保存方法
toExcel.saveExcel();
},
},
};
</script>
<style>
</style>