axios + vue导出excel文件
(使用到了elementUI框架)
<template><el-button type="primary" size="mini" @click="exportExcel">导出</el-button>
</template>
<script>
import API from '../api/api_dispatch'
export default {
data() {
return {
myCompanyId: ''
}
},
created() {
let userInfo = JSON.parse(window.sessionStorage.getItem('access-user'));
this.myCompanyId = userInfo.companyId;
},
methods: {
exportExcel() {
// 按需要可加上无数据不导出的判断(略)if (this.myCompanyId !== '') {
API.exportExcel({
companyId: this.myCompanyId
}).then(res => {
var blob = new Blob([res], {type: 'application/vnd.ms-excel;charset=utf-8'})
var downloadElement = document.createElement('a');
var href = window.URL.createObjectURL(blob); //创建下载的链接
downloadElement.href = href;
downloadElement.download = '导出文件.xls'; //下载后文件名
document.body.appendChild(downloadElement);
downloadElement.click(); //点击下载
document.body.removeChild(downloadElement); //下载完成移除元素
window.URL.revokeObjectURL(href); //释放掉blob对象
});
} else {
this.$message.error('操作异常');
}
}
}
}
</script>
api/api_dispatch.js:
import * as API from './'export default {
// 导出报表
exportExcel: params => {
return API.EXPORT('outOfDate/excel/export', params);
}
}
api/index.js:(省略了其他的GET、POST等方法)
import Env from './env'; // 声明接口地址文件import axios from 'axios'
//基地址
let base = Env.baseURL;
let instance = axios.create({
responseType: 'blob', //返回数据的格式,可选值为arraybuffer,blob,document,json,text,stream,默认值为json
})
// instance 添加一个请求拦截器
instance.interceptors.request.use(function (config) {
let user = JSON.parse(window.sessionStorage.getItem('access-user'));
config.headers.common['token'] = user.token
return config;
}, function (error) {
// Do something with request error
console.info("error: ");
console.info(error);
return Promise.reject(error);
})
// 导出
export const EXPORT = (url, params) => {
return instance({
method: 'get',
url: `${base}` + url,
params: params
}).then(res => {
return Promise.resolve(res.data)
})
}
以上是 axios + vue导出excel文件 的全部内容, 来源链接: utcz.com/z/379077.html