js批量下载excel文件

关键点
1.blob的type设置成表格
var blob = new Blob([res.data],{type : 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
2.请求header里面设置:responseType:'blob'

//此处用到了插件useAwait,和自己的接口请求函数download,慎重复制
 async fillDownload(item) {      
      //console.log(item, "item");
      let params = {
        deptCode: sessionStorage.getItem('deptId'),
        listStatus: 5,
        requireNo:item.requireNo,
        tableSeq: item.tableSeq,
      };
      let [err, res] = await useAwait(download(params));
      if (err) return;
      // console.log(res,'res')
      let blob = new Blob([res.data],{type : 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
      console.log(blob, "blob");
      // FileReader主要用于将文件内容读入内存
      let reader = new FileReader();
      reader.readAsDataURL(blob);
      // onload当读取操作成功完成时调用
      reader.onload =function(e){
        let a = document.createElement("a");
        // 获取文件名fileName
        let fileName = res.headers["content-disposition"].split("=");
        console.log(fileName,'fileName')
        fileName = fileName[1];
        fileName = fileName.replace(/"/g, "");
        a.download = fileName;
        a.href = e.target.result;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
      };
    },

内容不乱码,在axios中加 responseType:'blob'(此处为自己封装的axios,请勿复制)


export function download(params) {//下载填报数据
    return api({
        method: 'post',
        url: appServer.integratingInformation + 'excel/download',
        data:params,
        responseType:'blob'
    })
}

你可能感兴趣的:(js批量下载excel文件)