二進制數據轉化爲excel

原理就是通過a標籤的href屬性將二進制表格數據轉化爲表格,再通過download屬性將文件下載到本地;
需要注意的是接口請求的數據類型要設置爲 blob 類型 具體參考 axios https://www.npmjs.com/package/axios

  responseType: 'blob'

具體的代碼

   let url = window.URL.createObjectURL(res.data);
   let link = document.createElement('a');
   link.style.display = 'none';
   link.href = url;
   link.setAttribute('download', filename); // filename 自定義下載的表格名稱及後綴名;
   document.documentElement.appendChild(link);
   link.click();
   document.documentElement.removeChild(link);

完整的例子:

	 // 首先要引入axios
	  import axios from 'axios';
	// 組件內部新增方法
      downloadExl(filename) {
        axios({
            method: 'get',
            url: '/api/export',
            params: Object, // Object 導出接口所需要的參數對象 
            responseType: 'blob'
          }).then(res => {
            let url = window.URL.createObjectURL(res.data);
            let link = document.createElement('a');
            link.style.display = 'none';
            link.href = url;
            link.setAttribute('download', filename);
            document.documentElement.appendChild(link);
            link.click();
            document.documentElement.removeChild(link);
          }).catch(e => {
          	console.log('導出失敗')
          }).finally(() => {
          	console.log('不管導出成功/失敗')
          });
      },
發佈了53 篇原創文章 · 獲贊 15 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章