js实现excel文件下载

时间:2024-02-21 07:42:19
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);//下载文件
     
    },