vue中請求后端接口導出excel數據


 請求后端接口

一、點擊鏈接。

不需要token,也不需要傳給后台數據時

(1)window.location.href = ‘url’ 
(2)<a href='url' download=''></a>

二、需要攜帶請求頭token

這種方式就是后台將要導出的文件以文件流的方式返回給前端,前端通過blob去解析,再動態創建a標簽

(1)

import axios from "axios";

export default {
  data() {
    return {
      btnLoading: false
    };
  },
  methods: {
    // responseType 響應類型
    exportFile() {
      this.btnLoading = true;
      axios({
        method: 'get',
        url: '/api',
        headers: {
          token: '79faf82271944fe38c4f1d99be71bc9c'
        },
        responseType: "blob"
      })
        .then(res => {
          this.btnLoading = false;
          if (res.data.type) {
            // 文件下載
            const blob = new Blob([res.data], {
              type: "application/vnd.ms-excel"
            });
            let link = document.createElement('a');
            link.href = URL.createObjectURL(blob);
            link.setAttribute('download', '導出文件.xlsx');
            link.click();
            link = null;
            this.$message.success('導出成功');
          } else {
            // 返回json
            this.$message.warning(res.data.msg);
          }
        })
        .catch(err => {
          this.btnLoading = false;
          this.$message.error("下載失敗");
        });
    }
  }
};

 (3)解析后台返回的文件流(通過param傳數據給后台)

這種方式就是后台將要導出的文件以文件流的方式返回給前端,前端通過blob去解析,再動態創建a標簽

var param = {
  queryString:this.orderQuerySearch,
  canal:this.orderType
};
var url = '/order/excel'
this.$axios.post(url, param, {responseType: 'arraybuffer'}).then(res => {
  let content = res.data; // 文件流
  let blob = new Blob([content],{type: 'application/octet-stream'});
  let fileName = 'filename.xls';
 // 如果后端返回文件名
 // let contentDisposition = res.headers['content-disposition'];
 // let fileName = decodeURI(contentDisposition.split('=')[1]);
  if ('download' in document.createElement('a')) {  // 非IE下載
     let link = document.createElement('a');
     link.download = fileName;
     link.style.display = 'none';
     link.href = URL.createObjectURL(blob);
     document.body.appendChild(link);
     link.click();
     URL.revokeObjectURL(link.href) ; // 釋放URL 對象
     document.body.removeChild(link);
  } else {  // IE10+下載
     navigator.msSaveBlob(blob,fileName);
  }
})

 接收數據前端實現

這種方式就是后台只需提供對應的數據即可,前端動態生成表格數據,再格式化。

let excel = '<table>';
// 生成表頭
let row = '<tr>' +
  '<td>標題1</td>' +
  '<td>標題2</td>' +
  '<td>標題3</td>' +
  '</tr>';
excel += row + '</tr>';
// 循環生成表身
for(let i = 0 ; i < this.excelData.length ; i++ ){
  excel += '<tr>';
  for(let item in this.excelData[i]){
    //增加\t為了不讓表格顯示科學計數法或者其他格式
    if (!this.excelData[i][item]) {
      this.excelData[i][item] = '';
    }
    excel +=`<td>${ this.excelData[i][item] + '\t'}</td>`;
  }
  excel +='</tr>';
}
excel += '</table>';
//下載的表格模板數據
var excelFile = '<html xmlns:o="urn:schemas-microsoft-com:office:office" ' +
  'xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40">';
excelFile += '<meta http-equiv="content-type" content="application/vnd.ms-excel; charset=UTF-8">';
excelFile += '<meta http-equiv="content-type" content="application/vnd.ms-excel"';
excelFile += ' charset="UTF-8">';
excelFile += '<head>';
excelFile += '<!--[if gte mso 9]>';
excelFile += '<xml>';
excelFile += '<x:ExcelWorkbook>';
excelFile += '<x:ExcelWorksheets>';
excelFile += '<x:ExcelWorksheet>';
excelFile += '<x:Name>';
excelFile += 'sheet';
excelFile += '</x:Name>';
excelFile += '<x:WorksheetOptions>';
excelFile += '<x:DisplayGridlines/>';
excelFile += '</x:WorksheetOptions>';
excelFile += '</x:ExcelWorksheet>';
excelFile += '</x:ExcelWorksheets>';
excelFile += '</x:ExcelWorkbook>';
excelFile += '</xml>';
excelFile += '<![endif]-->';
excelFile += '</head>';
excelFile += '<body>';
excelFile += excel;
excelFile += '</body>';
excelFile += '</html>';
//下載模板
let uri = 'data:application/vnd.ms-excelcharset=utf-8,' + encodeURIComponent(excelFile);
let link = document.createElement('a');
link.href = uri;
link.style = 'visibility:hidden';
let myDate = new Date();
let time = myDate.toLocaleDateString().split('/').join('-');
link.download = 'fileName' + time + '.xls';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM