前端接收后端返回的文件流導出Excel


需求:接收后端返回的文件流導出Excel

自己項目中遇到過,親測有效

情況二使用過程中解決的問題:

1.直接接受的文件流下載格式為txt且亂碼。需要通過 下面這句代碼來轉成Excel:

 let url = new Blob([xmlHttp.response], { type: 'application/vnd.ms-excel' });

2.文件名亂碼,顯示數字單詞組成的隨機字符串。需要后端在header中返回文件名,轉義獲取

//文件名
link.download = decodeURIComponent(xmlHttp.getResponseHeader("content-disposition").split(";")[1].split("filename=")[1]);

3.IE或者360兼容模式下,無法下載

//兼容IE
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
let url = new Blob([xmlHttp.response], { type: 'application/vnd.ms-excel' });
window.navigator.msSaveOrOpenBlob(url, decodeURIComponent(xmlHttp.getResponseHeader("content-disposition").split(";")[1].split("filename=")[1]));
}

情況一:無需傳token

href:接口地址
queryValues:傳參
export function batchExport(href, queryValues) {
const link = document.createElement('a');
link.href = `${href}?${qs.stringify(queryValues)}`;
link.download = '導出.xls';
link.click();
}

情況二:header中傳token,兼容IE,360兼容模式,文件名不會亂碼

decodeURIComponent(xmlHttp.getResponseHeader("content-disposition").split(";")[1].split("filename=")[1] //從header中獲取文件名,需后端提供,如果是前端定義的文件名,可直接 link.download = '文件名XXX'
href:接口地址
queryValues:傳參
export function batchExport(href, queryValues) {
  let xmlHttp = null;
  if (window.ActiveXObject) {
    xmlHttp = new window.ActiveXObject('Microsoft.XMLHTTP');
} else if (window.XMLHttpRequest) {
    xmlHttp = new XMLHttpRequest();
}
  if (xmlHttp != null) {
xmlHttp.ContentType = 'application/vnd.ms-excel';
xmlHttp.open('get', `${href}?${qs.stringify(queryValues)}`, true);
xmlHttp.setRequestHeader('token', getUserInfo().token);
xmlHttp.responseType = 'blob';
xmlHttp.send();
xmlHttp.onreadystatechange = doResult;
}

  function doResult() {
    let link = document.createElement('a');
    link.style.display = 'none';
    if (xmlHttp.readyState === 4) {
      if (xmlHttp.status === 200) {
        //兼容IE
        if (window.navigator && window.navigator.msSaveOrOpenBlob) {
          let url = new Blob([xmlHttp.response], { type: 'application/vnd.ms-excel' });
window.navigator.msSaveOrOpenBlob(url, decodeURIComponent(xmlHttp.getResponseHeader("content-disposition").split(";")[1].split("filename=")[1]));
}else{
      //其他瀏覽器
let url = createObjectURL((new Blob([xmlHttp.response],
{ type: 'application/vnd.ms-excel' })));
        //文件名
link.download = decodeURIComponent(xmlHttp.getResponseHeader("content-disposition").split(";")[1].split("filename=")[1]);
link.href = url;
link.click();
}
      } else {
        message.error('下載失敗');
}
    }
  }
}

 每天進步一點點~


免責聲明!

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



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