如何将.xlsx数据作为 Blob 保存到文件

How to save .xlsx data to file as a blob

本文关键字:Blob 存到文件 数据 xlsx      更新时间:2023-09-26

我对这个问题有一个类似的问题(Javascript:导出大型文本/csv文件崩溃谷歌浏览器):

我正在尝试保存由excelbuilder.jsEB.createFile()功能创建的数据。如果我将文件数据作为链接的href属性值,它可以工作。但是,当数据很大时,它会崩溃Chrome浏览器。代码是这样的:

//generate a temp <a /> tag
var link = document.createElement("a");
link.href = 'data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,' + encodeURIComponent(data);
link.style = "visibility:hidden";
link.download = fileName;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);

我使用 excelbuilder 创建数据的代码.js如下所示:

var artistWorkbook = EB.createWorkbook();
var albumList = artistWorkbook.createWorksheet({name: 'Album List'});
albumList.setData(originalData); 
artistWorkbook.addWorksheet(albumList);
var data = EB.createFile(artistWorkbook);

正如类似问题的回答所建议的那样(Javascript:导出大型文本/csv文件使Google Chrome崩溃),需要创建一个blob。

我的问题是,文件中保存的内容不是可以通过Excel打开的有效Excel文件。我用来保存blob的代码是这样的:

var blob = new Blob(
    [data],
    {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,"}
);
// Programatically create a link and click it:
var a = document.createElement("a");
a.href = URL.createObjectURL(blob);
a.download = fileName;
a.click();

如果我将上述代码中的[data]替换为[Base64.decode(data)],则保存的文件中的内容看起来更像预期的excel数据,但仍然无法通过Excel打开。

我和你有同样的问题。事实证明,您需要将Excel数据文件转换为ArrayBuffer。

var blob = new Blob([s2ab(atob(data))], {
    type: ''
});
href = URL.createObjectURL(blob);

s2ab(字符串到数组缓冲区)方法(我从 https://github.com/SheetJS/js-xlsx/blob/master/README.md 获得)是:

function s2ab(s) {
  var buf = new ArrayBuffer(s.length);
  var view = new Uint8Array(buf);
  for (var i=0; i!=s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
  return buf;
}

上面的答案是正确的。请确保在 base64 的数据变量中有一个字符串数据,没有任何前缀或类似的东西只是原始数据。

这是我在服务器端(asp.net mvc 核心)所做的:

string path = Path.Combine(folder, fileName);
Byte[] bytes = System.IO.File.ReadAllBytes(path);
string base64 = Convert.ToBase64String(bytes);

在客户端,我执行了以下代码:

const xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.setRequestHeader("Content-Type", "text/plain");
xhr.onload = () => {
    var bin = atob(xhr.response);
    var ab = s2ab(bin); // from example above
    var blob = new Blob([ab], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;' });
    var link = document.createElement('a');
    link.href = window.URL.createObjectURL(blob);
    link.download = 'demo.xlsx';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
};
xhr.send();

它对我来说非常有效。

我找到了一个适合我的解决方案:

const handleDownload = async () => {
   const req = await axios({
     method: "get",
     url: `/companies/${company.id}/data`,
     responseType: "blob",
   });
   var blob = new Blob([req.data], {
     type: req.headers["content-type"],
   });
   const link = document.createElement("a");
   link.href = window.URL.createObjectURL(blob);
   link.download = `report_${new Date().getTime()}.xlsx`;
   link.click();
 };

我只是指出一个响应类型:"blob"

这适用于: v0.14.0 of https://github.com/SheetJS/js-xlsx

/* generate array buffer */
var wbout = XLSX.write(wb, {type:"array", bookType:'xlsx'});
/* create data URL */
var url = URL.createObjectURL(new Blob([wbout], {type: 'application/octet-stream'}));
/* trigger download with chrome API */
chrome.downloads.download({ url: url, filename: "testsheet.xlsx", saveAs: true });
这是我

使用 fetch API 实现的。服务器终结点发送字节流,客户端接收字节数组并从中创建 Blob。然后将生成一个.xlsx文件。

return fetch(fullUrlEndpoint, options)
  .then((res) => {
    if (!res.ok) {
      const responseStatusText = res.statusText
      const errorMessage = `${responseStatusText}`
      throw new Error(errorMessage);
    }
    return res.arrayBuffer();
  })
    .then((ab) => {
      // BE endpoint sends a readable stream of bytes
      const byteArray = new Uint8Array(ab);
      const a = window.document.createElement('a');
      a.href = window.URL.createObjectURL(
        new Blob([byteArray], {
          type:
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        }),
      );
      a.download = `${fileName}.XLSX`;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
    })
    .catch(error => {
      throw new Error('Error occurred:' + error);
    });

对我来说是解决方案。

步数:1

<a onclick="exportAsExcel()">Export to excel</a>

步数:2

我正在使用文件保护程序库。

阅读更多: https://www.npmjs.com/package/file-saver

npm i file-saver

步数:3

let FileSaver = require('file-saver'); // path to file-saver
function exportAsExcel() {
    let dataBlob = '...kAAAAFAAIcmtzaGVldHMvc2hlZXQxLnhtbFBLBQYAAAAACQAJAD8CAADdGAAAAAA='; // If have ; You should be split get blob data only
    this.downloadFile(dataBlob);
}
function downloadFile(blobContent){
    let blob = new Blob([base64toBlob(blobContent, 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')], {});
    FileSaver.saveAs(blob, 'report.xlsx');
}
function base64toBlob(base64Data, contentType) {
    contentType = contentType || '';
    let sliceSize = 1024;
    let byteCharacters = atob(base64Data);
    let bytesLength = byteCharacters.length;
    let slicesCount = Math.ceil(bytesLength / sliceSize);
    let byteArrays = new Array(slicesCount);
    for (let sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex) {
        let begin = sliceIndex * sliceSize;
        let end = Math.min(begin + sliceSize, bytesLength);
        let bytes = new Array(end - begin);
        for (var offset = begin, i = 0; offset < end; ++i, ++offset) {
            bytes[i] = byteCharacters[offset].charCodeAt(0);
        }
        byteArrays[sliceIndex] = new Uint8Array(bytes);
    }
    return new Blob(byteArrays, { type: contentType });
}

为我工作。^^

尝试FileSaver.js库。 它可能会有所帮助。

https://github.com/eligrey/FileSaver.js/

这个答案取决于前端和后端都具有兼容的返回对象,因此给出了前端和后端逻辑。确保后端返回数据采用 base64 编码,以便以下逻辑正常工作。

// Backend code written in nodejs to generate XLS from CSV
import * as XLSX from 'xlsx';
export const convertCsvToExcelBuffer = (csvString: string) => {
  const arrayOfArrayCsv = csvString.split("'n").map((row: string) => {
    return row.split(",")
  });
  const wb = XLSX.utils.book_new();
  const newWs = XLSX.utils.aoa_to_sheet(arrayOfArrayCsv);
  XLSX.utils.book_append_sheet(wb, newWs);
  const rawExcel = XLSX.write(wb, { type: 'base64' })
  // set res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') 
  // to include content type information to frontend. 
  return rawExcel
}
//frontend logic to get the backend response and download file. 
// function from Ron T's answer which gets a string from ArrayBuffer. 
const s2ab = (s) => {
  var buf = new ArrayBuffer(s.length);
  var view = new Uint8Array(buf);
  for (var i = 0; i !== s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
  return buf;
};
const downloadExcelInBrowser = ()=>{
  const excelFileData = await backendCall();
  const decodedFileData = atob(excelFileData.data);
  const arrayBufferContent = s2ab(decodedFileData); // from example above
  const blob = new Blob([arrayBufferContent], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;' });
  var URL = window.URL || window.webkitURL;
  var downloadUrl = URL.createObjectURL(fileBlob);
  if (filename) {
    // use HTML5 a[download] attribute to specify filename
    var a = document.createElement('a');
    // safari doesn't support this yet
    if (typeof a.download === 'undefined') {
      window.location.href = downloadUrl;
    } else {
      a.href = downloadUrl;
      a.download = 'test.xlsx';
      document.body.appendChild(a);
      a.click();
    }
  } else {
    window.location.href = downloadUrl;
  }
}

如果您使用的是打字稿,那么这里有一个如何将数组转换为XLSX并下载它的工作示例。

const fileName = "CustomersTemplate";
    const fileExtension = ".xlsx";
    const fullFileName = fileName.concat(fileExtension);
    const workBook : WorkBook = utils.book_new();
    const content : WorkSheet = utils.json_to_sheet([{"column 1": "data", "column 2": "data"}]);
    utils.book_append_sheet(workBook, content, fileName);
    const buffer : any = writeFile(workBook, fullFileName);
    const data : Blob = new Blob(buffer, { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;" });
    const url = URL.createObjectURL(data); //some browser may use window.URL
    
    const a = document.createElement("a");
    document.body.appendChild(a);
    a.href = url;
    a.download = fullFileName;
    a.click();
    
    setTimeout(() => {
      window.URL.revokeObjectURL(url);
      document.body.removeChild(a);
    }, 0);