vue 下载excel表格

本文介绍了如何在Vue.js应用中实现从服务器下载Excel表格文件。通过结合HTML5的`a`标签和JavaScript的Blob对象,创建一个可以下载的链接,用户点击后即可下载Excel数据。同时讨论了Vue中处理文件下载的注意事项和最佳实践。
摘要由CSDN通过智能技术生成
  <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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值