文件导出 记录

文件的导出格式为excel

因为导出组件为封装的组件,所以主要应用的是父子传值,封装组件如下:

HTML

<template>
  <el-button @click="exportChecked"  type="primary" size="mini">{{buttonName}}</el-button>
</template>

JS

<script>
  import request from '@/utils/request'
  export default {
    name: 'exportModular',
    data() {
      return {
        nubmer: 50000
      }
    },
    props: {
      totals: 0, // 父组件传递的表格数据总数,限制导出数量不大于50000
      url: {
        type: String,
        default: '/alarm/record/download'
      },
      params: { // 参数
        type: Object
      },
      method: {
        type: String,
        default: 'POST'
      },
      responseType: {
        type: String,
        default: 'blob'
      },
      parameter: {
        type: String,
        default: '泉州平台'
      },
      fileName: {
        type: String,
        default: '泉州平台'
      },
      buttonName: {
        type: String,
        default: '导出'
      },
      fileType: {
        type: String,
        default: '.zip'
      }
    },
    methods: {
      // 导出
      exportChecked() {
        if (this.totals < this.nubmer) { // 限制文件大小
          this.$emit('down')
          const param = {
            url: this.url,
            method: this.method,
            data: this.params,
            responseType: this.responseType
          }
          this.exportAjax(param).then((res) => {
            this.downloads(res)
          }).catch((res) => {
            console.log(res.type)
            this.downloads(res)
          })
        } else {
          this.$message({
            message: '导出数据不能大于' + this.nubmer,
            type: 'warning',
            duration: '1500'
          })
        }
      },

      downloads(data) {
        if (!data) {
          return
        }
        console.log('9999999999999999999999')
        console.log(data)
        const url = window.URL.createObjectURL(new Blob([data]), { type: data.type })
        const link = document.createElement('a')
        link.style.display = 'none'
        link.href = url
        link.setAttribute('download', this.parameter + this.fileType)
        document.body.appendChild(link)
        link.click()
      },

      exportAjax(params) {
        return request({
          responseType: params.responseType,
          url: params.url,
          method: params.method,
          params: params.data
        })
      }
    }
  }
</script>

因为buttom使用的是elementUI,所以这里没有样式设置。

当点击导出按钮时首先会做一个大小限制的判断,然后根据传递的数据做请求,即exportAjax方法,其中牵扯一个request

方法,个人还不是很理解,再研究吧,后续奉上代码,downloads方法中用到了Blob,想了解的可以点这里

在父组件中调用:

<export-modular-post url="/statistics/adas/excel" :totals="total" :params="exportParams" :parameter="exportFileName" file-type=".xls"></export-modular-post>

详细的传递参数示例

computed: {
    exportParams() {
      return {
        startTime: this.tableQuery.startTime,
        endTime: this.tableQuery.endTime,
        alarmType: this.tableQuery.alarmType,
        vehicleId: this.tableQuery.vehicleId,
        hendlerStatus: this.tableQuery.hendlerStatus,
        handlerTypeCode: this.tableQuery.handlerTypeCode
      }
    },
    exportFileName() {
      return '驾驶员行为报警处理统计' + this.tableQuery.startTime + '-' + this.tableQuery.endTime
    }
  }

total为接口响应数据的总个数

下面奉上request请求

import axios from 'axios'
import { Message, MessageBox } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import qs from 'qs'

// create an axios instance
const service = axios.create({
  baseURL: process.env.BASE_API, // api的base_url
  timeout: 100000 // request timeout
})

// 发送请求前对请求数据进行处理
service.defaults.transformRequest = [function(data) {
  /**
   * axios默认请求Context-type是application/json,也就是默认发送json格式参数,后台需要用@RequestBody进行处理
   * 这里统一用qs对请求参数进行格式化成FormData格式
   */
  return qs.stringify(data)
}]

// 请求拦截器
service.interceptors.request.use(config => {
  // Do something before request is sent
  if (store.getters.token) {
    // 让每个请求携带token-- ['XN-Auth']为自定义Header key
    config.headers['XN-Auth'] = getToken()
  }
  return config
}, error => {
  // Do something with request error
  Promise.reject(error)
})

// 响应拦截器
service.interceptors.response.use(
  /* response => {
    return response.data
  }, */
  /**
   * 通过在response里自定义code来标示请求状态,这里根据不同的code情况做相应的处理<br>
   * 也可以通过XMLHttpRequest对象状态码标识进行相应的处理
   */
  response => {
    const res = response.data
    if (res.code !== 0) {
      // 1004:Token 过期了
      if (res.code === 1004) {
        // 请自行在引入 MessageBox
        MessageBox.confirm('你的登录认证失效,可以取消继续留在该页面,或者重新登录', '确定登出', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          store.dispatch('FedLogOut').then(() => {
            location.reload() // 为了重新实例化vue-router对象 避免bug
          })
        })
        // 统一处理系统异常,不再发给上层业务
      } else if (res.code === 1001 || res.code === 1002 || res.code === 1003 || res.code === 1005 || 
        res.code === 1006 || res.code === 1007 || res.code === 1008 || res.code === 1009 || res.code === 1010) {
        Message({
          message: res.msg,
          type: 'error',
          duration: 5 * 1000
        })
      } else { // 对其它返回状态码是非0的情况,这里捕获并返回reject的Promise对象,上层业务通过catch处理异常信息
        return Promise.reject(res)
      }
    } else {
      return res
    }
  },
  error => { // 对XMLHttpRequest状态码非200的处理
    console.log('err:' + JSON.stringify(error)) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  })

export default service

猜你喜欢

转载自blog.csdn.net/lwx931449660/article/details/88683087
今日推荐