<script>
//excel请求接口
export function downloadSummaryToExcel(params){
return axios.request({
url:'',
methods:'get',
responseType:'blob',
params,
responseFull:true
})
}
/请求配置
class HttpRequest{
constructor(baseUrl = config.baseUrl,useKey = true){
this.baseUrl = baseUrl
this.useKey = useKey
}
getInsideConfig(){
const config = {
baseURL : this.baseUrl,
headers:{}
}
return config
}
interceptors(instance,url,responseFull){
///
responseFun = responseFunll || false
///
instance.interceptors.request.use(config =>{
if(this.useKey && store.state.key){
config.headers = config.headers || {}
config.headers.Authorization = store.state.key
}
return config
},error=>{
return Promise.reject(error)
})
instance.interceptors.response.use(res => {
closeLoadingInstance()
//服务器正常结果返回给前端时走的成功回调
const {data} = res
//
return responseFull ? res : data
},error=>{
closeLoadingInstance()
return Promise.reject( (error.response && error.response.data) || error)
})
}
request(options){
const loadingInstance = Loading.service({fullscreen:false,text:'加载中...',customClass:"common-loading-class",background:"rgba(0,0,0,0)"})
///关键代码
loadingInstanceStack.push(loadingInstance)
loadingCount++
//
options = options || {}
const instance = axios.create()
options = Object.assign(this.getInsideConfig(),options)
是否在响应拦截器中返回res.data 或者直接返回res
const responseFull = options.responseFull
this.interceptors(instance,options.url,responseFull)
/
return instance(options)
}
}
export default HttpRequest
//点击下载excel方法
async exportExcel(){
try{
let {data,headers} = await downloadSummaryToExcel({
id:this.id
})
if(res.type === 'application/json'){
const fileReader = new FileReader();
fileReader.onload = function(){
try{
const {message} = JSON.PARSE(fileReader.result)
this.$message.error(message || '失败')
}catch(e){
this.$message.error(message || '失败')
}
}
fileReader.readAsText(res)
}else{
if(data){
const blob = new Blob([data],{type:"application/vnd.ms-excel"});
let fileName = '';
const content = headers['content-disposition']
const filenameKeyVal = content.split(';')[1]
if(filenameKeyVal){
if(filenameKeyVal.split('=')[1]){
fileName = decodeURIComponent(filenameKeyVal.split('=')[1])
}
}
if('download' in document.createElement('a')){
//非IE下载
const elink = document.createElement('a')
elink.download = fileName;
elink.style.display = 'none';
elink.href = URL.createObjectURL(blob);
document.body.appendChild(elink);
elink.click();
elink.remove();
URL.revokeObjectURL(elink.href);//释放URL对象
}else{
//IE10 + 下载
navigator.msSaveBlob(blob,fileName + '.xls');
}
}else{
this.$message.error('失败')
}
}
}catch(e){
console.log(e)
}
}
</script>
vue 下载excel表格
最新推荐文章于 2024-08-01 16:49:44 发布
本文介绍了如何在Vue.js应用中实现从服务器下载Excel表格文件。通过结合HTML5的`a`标签和JavaScript的Blob对象,创建一个可以下载的链接,用户点击后即可下载Excel数据。同时讨论了Vue中处理文件下载的注意事项和最佳实践。
摘要由CSDN通过智能技术生成