Download Repack Excel File From Byte Array Angular File
import { Injectable } from '@angular/core'; import { saveAs } from 'file-saver'; @Injectable({ providedIn: 'root' }) export class ExcelDownloadService { // MIME type for .xlsx files private readonly EXCEL_TYPE = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'; private readonly EXCEL_EXTENSION = '.xlsx'; public downloadExcel(byteArray: any, fileName: string): void { // 1. Create a Blob from the byte array const data: Blob = new Blob([byteArray], { type: this.EXCEL_TYPE }); // 2. Use file-saver to initiate download saveAs(data, `${fileName}_${new Date().getTime()}${this.EXCEL_EXTENSION}`); } } Use code with caution. Step 2: Fetching the Byte Array from an API
The core logic involves wrapping the byte array in a object with the correct MIME type and then triggering the browser's download mechanism. Step 1: Create the Excel Service download excel file from byte array angular
// In your DataService getExcelReport(): Observable { return this.http.get('api/reports/excel', { responseType: 'blob' // Essential to receive binary data }); } Use code with caution. 3. Handling Base64 Encoded Strings import { Injectable } from '@angular/core'; import {
npm install file-saver npm install @types/file-saver --save-dev Use code with caution. 2. Implementation: From Byte Array to Excel Step 2: Fetching the Byte Array from an
// Decoding Base64 to Blob const byteCharacters = atob(base64Data); const byteArray = new Uint8Array(byteCharacters.length); for (let i = 0; i < byteCharacters.length; i++) { byteArray[i] = byteCharacters.charCodeAt(i); } const blob = new Blob([byteArray], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }); Use code with caution. 4. Native Browser Approach (No Libraries)