'How to convert a raw data excel to a downloadable one?

I receive a raw data of an excel when I send my http request. I am using fileSaver package to save base64 files like pdf (turned into a blob) with it and it works alright. what I receive is as the image below. My question is how can I turn this into saveable blob without data corruption? note that when I save this sting as file in postman it saves fine. this approach did not work and saves a corrupt excel that cannot be opened:

      var blob = new Blob([s2ab(response)], {
        type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
      });

      FileSaver.saveAs(blob, action.payload.culture + ".xlsx");

enter image description here



Solution 1:[1]

Solved in this way: before you do anything add arrayBuffer as response-type to your http req header.

firstly convert the binary of arraybuffer to base64:

export function arrayBufferToBase64(buffer: ArrayBufferLike) {
  let binary = "";
  let bytes = new Uint8Array(buffer);
  let len = bytes.byteLength;
  for (let i = 0; i < len; i++) {
    binary += String.fromCharCode(bytes[i]);
  }
  return window.btoa(binary);
}

then decode this base64 to a blob:

export const base64toBlob = (b64Data: string, contentType = "", sliceSize = 512): Blob => {
  const byteCharacters = atob(b64Data);
  const byteArrays = [];

  for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
    const slice = byteCharacters.slice(offset, offset + sliceSize);

    const byteNumbers = new Array(slice.length);
    for (let i = 0; i < slice.length; i++) {
      byteNumbers[i] = slice.charCodeAt(i);
    }

    const byteArray = new Uint8Array(byteNumbers);

    byteArrays.push(byteArray);
  }

  const blob = new Blob(byteArrays, { type: contentType });
  return blob;
};

Now download it:

  const blob = base64toBlob(arrayBufferToBase64(response.data));
  FileSaver.saveAs(blob, `${orderType}_${formatedDates.from}_${formatedDates.to}.xlsx`);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Alireza tk