js實現excel文件下載


1.文件流下載文件:
/**
 * @description: 
 * @param {type} fileName-文件名 suffix-后綴名
 * @return: 
 */
export function axiosPostExport (url, data, fileName, suffix='.xlsx') {
    url = getUrlIfUseMock(url, {method: 'POST'});
    return axios({
        method: 'post',
        url,
        data,
        responseType: 'blob'
    }).then(res => {
        return res.data
    }).then(res => {
        const content = res
        const fileNamex = fileName + '-' + moment().format('YYYYMMDDHHmmss') + suffix
        const blob = new Blob([content])
        if ('download' in document.createElement('a')) { // 非IE下載
            const elink = document.createElement('a')
            elink.download = fileNamex
            elink.style.display = 'none'
            elink.href = URL.createObjectURL(blob)
            document.body.appendChild(elink)
            elink.click()
            URL.revokeObjectURL(elink.href) // 釋放URL 對象
            document.body.removeChild(elink)
        } else { // IE10+下載
            navigator.msSaveBlob(blob, fileNamex)
        }
    }).catch(error => console.log(error))
}
或者:let url = `/admin/user/list/all/export?countryCode=310101`;
        let xhr = new XMLHttpRequest();
        xhr.open("POST", url, true); // 也可以使用POST方式,根據接口
        xhr.responseType = "blob"; // 返回類型blob,XMLHttpRequest支持二進制流類型
        xhr.onload = function() {
          if (this.status === 200) {
            let blob = this.response; //使用response作為返回,而非responseText
            let reader = new FileReader();
            reader.readAsDataURL(blob); // 轉換為base64,可以直接放入a標簽href
            reader.onload = function(e) {
              // 轉換完成,創建一個a標簽用於下載
              let a = document.createElement("a");
              a.download = "原始數據.xls";
              a.href = e.target.result;
              a.click();
            };
          }
        };
        xhr.send("countryCode=310101");
2.一般文件下載:
<button class="layui-btn search" style="margin-left: 50px;" v-if="hash==2"><a href="/admin/user/list/all/export" download="userlist.xls" style="color: #fff;">導出</a></button>
3.與2實現效果差不多
var $form = $('<form method="post"></form>');
$form.attr('action', '/admin/user/list/all/export?countryCode=310101');
    $form.appendTo($('body'));
$form.submit();
    $form.remove();
4.直接open()打開url鏈接下載,這時候接口也是返回來的二進制的數據:
 download(file){//下載文件
      // console.log("fileL:",file);
      const index = this.fileList1.indexOf(file);
      const filedir=this.filedirList[index];
      const that = this;
      let url = `${this.urlDownload}?fileName=${file.name}&filedir=${filedir}`;
      window.open(url);//下載文件
     
    },

 


免責聲明!

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



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