base64格式excel文件生成及下载

文件生成

      // Worksheet名
      let worksheet = 'Sheet1'
      let uri = 'data:application/vnd.ms-excel;base64,'
      // 输出base64编码
      let base64 = s => window.btoa(unescape(encodeURIComponent(s)))
   // 下载的表格模板数据
     let template = `
        
        
        
        表格内容
` downloadFile(filename, uri + base64(template))

文件下载

downloadFile(‘文件名称’, ‘base64地址’);
function  downloadFile (fileName, content) {
      const blob = base64ToBlob(content); // new Blob([content]);
      if (window.navigator.msSaveOrOpenBlob) {
        navigator.msSaveBlob(blob, fileName);
      } else {
        const link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        link.download = fileName;

        //此写法兼容可火狐浏览器
        document.body.appendChild(link);
        const evt = document.createEvent("MouseEvents");
        evt.initEvent("click", false, false);
        link.dispatchEvent(evt);
        document.body.removeChild(link);
      }
    }
   function  base64ToBlob (code) {
      const parts = code.split(';base64,');
      const contentType = parts[0].split(':')[1];
      const raw = window.atob(parts[1]);
      const rawLength = raw.length;
      const uInt8Array = new Uint8Array(rawLength);
      for (let i = 0; i < rawLength; ++i) {
        uInt8Array[i] = raw.charCodeAt(i);
      }
      return new Blob([uInt8Array], { type: contentType });
    }

你可能感兴趣的:(base64格式excel文件生成及下载)