項目中導出excel文件很常見,分為get和post方式,get相對簡單些,在url后面拼接需要的參數
get方式
get請求方式傳參如果是對象類型 需要 用encodeURI(JSON.stringify(params)) 轉換一下
get請求方式拼接參數長度上限為2083,超過這個長度導出excel失敗
post方式請求返回的是表格流文件,需要使用blob對象指定要讀取的數據,在此記錄下
<div class="same-head"> <el-button type="success" size="mini" @click="hadnleAdd">登記系統信息</el-button> <el-button type="primary" size="mini" @click="hadnleImport">導入</el-button> <el-button type="primary" size="mini" @click="hadnleExport">導出</el-button> <el-button type="primary" size="mini" @click="hadnleDownload">下載模板</el-button> </div>
exportFile() { let that = this; this.$http({ method: 'post', url: this.$api.projectInfo.exportExcel, data: JSON.stringify(this.exportData), responseType: 'blob',//服務器返回的數據類型 }).then((res) => { console.log(res, '響應狀態'); let blob = new Blob([res], {type:"application/force-download"}) // Blob 對象表示一個不可變、原始數據的類文件對象 console.log(blob); let fileReader = new FileReader() // FileReader 對象允許Web應用程序異步讀取存儲在用戶計算機上的文件的內容 fileReader.readAsDataURL(blob) //開始讀取指定的Blob中的內容。一旦完成,result屬性中將包含一個data: URL格式的Base64字符串以表示所讀取文件的內容 fileReader.onload = (e) => { let a = document.createElement('a') a.download = `項目應用信息台賬.xlsx` a.href = e.target.result document.body.appendChild(a) a.click() document.body.removeChild(a) } }).catch(err => { console.log(err); }) }