(使用到了elementUI框架)ios
<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:json
import * as API from './' export default { // 導出報表 exportExcel: params => { return API.EXPORT('outOfDate/excel/export', params); } }
api/index.js:(省略了其餘的GET、POST等方法)axios
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) }) }