Angular fixes corrupted Excel files

My current project involves using Angular to call an API and retrieve a byte[] of an Excel file. However, I am facing issues with the file becoming corrupted when I convert the byte[] to a file using blob. Can anyone offer assistance with this problem?
My Angular version is 9.

service.ts:

downloadFile(req?: any): any {
    const options = createRequestOption(req);
    return this.http.get(`${this.resourceUrl}/print`, {
       params: options,
       responseType:'blob' })
   .toPromise();
}

component.ts:

import {saveAs} from 'file-saver';

export():void{
this.exportService.downloadFile({}) .then((blob:any)=> {
saveAs(blob, 'test.xlsx');
});
}

API response

Link to view my Excel file:

Answer №1

Kindly update your response type in the following manner:

fetchFile(req?: any): any {
    const options = createRequestOption(req);
    return this.http.get(`${this.resourceUrl}/download`, {
       params: options,
       responseType: ResponseContentType.Blob })
   .toPromise();
}

Revise your code to the one provided below and include Blob

exportData():void{
    this.exportService.fetchFile({}) .then((data:any)=> {

let blob = new Blob([data], {type: 'text/csv'});
        saveAs(blob, 'exportedData.xlsx');
        });
     }

Answer №2

I prefer not to do this on my own, thank you. I am uncertain about the best answer but this seems to work.

 convertToByte(file = ''): Observable<HttpResponse<string>>{
  return this.http.get(`${this.resourceUrl}/convertToByte`, {
    responseType: 'text',
    observe: 'response'
  }).pipe(map((res: HttpResponse<string>) => this.byteToFile(res,file)));
}


private byteToFile(res: HttpResponse<string>,file:string): HttpResponse<string> {
    if(res.body){
     const fileName = file;
     const a = document.createElement('a');
     document.body.appendChild(a);
     const sliceSize = 512;

     const byteCharacters = res.body;
     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: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
    const fileURL = window.URL.createObjectURL(blob);
    a.href = fileURL;
    a.download = fileName;
    a.click();
  }
  return res.clone();
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating cascading select fields in Angular using form controls

Encountering a peculiar issue with Angular Reactive Forms and a dependent drop-down list, undoubtedly stemming from my lack of expertise. I aim to establish the options in the second drop-down reliant on the selection in the first drop-down. Upon changing ...

What could be causing my NodeJS Backend to not retrieve the data properly?

For a current project, I am tasked with building a mobile application using Flutter for the frontend and NodeJS for the backend. To facilitate this, I have acquired a VPS from OVHcloud running Ubuntu 20.04. Following various tutorials, I set up a server as ...

Displaying text and concealing image when hovering over a column in an angular2 table

I am currently using a table to showcase a series of items for my data. Each data entry includes an action column with images. I would like to implement a feature where hovering over an image hides the image and reveals text, and vice versa (showing the im ...

Get notified about the number of cells you've selected by simply dragging on a table

Is there a way to display the number of selected cells in a table when dragging with the mouse? I have a table set up, and I'd like to create an alert that shows how many cells are selected while dragging. Here is the link to my fiddle: http://jsfiddl ...

Achieve HTTPS with angular-cli when running ng serve

It seems like the code snippet below is not working as expected. ng serve --ssl true --ssl-key <key-path> --ssl-cert <cert-path> Even when creating the Certificate and key by placing them in the default ssl directory, there is still no effect ...

Angular2: Ensuring Sequential Execution Line by Line - A Comprehensive Guide

I have a designed an Angular2 Navbar Component that features a logout button: import { Component, OnInit } from '@angular/core'; import { LoginService } from '../login.service'; import { Router } from '@angular/router'; @Co ...

How do RxJS collection keys compare?

Is there a more efficient way to compare two arrays in RxJS? Let's say we have two separate arrays of objects. For example: A1: [{ name: 'Sue', age: 25 }, { name: 'Joe', age: 30 }, { name: 'Frank', age: 25 }, { name: & ...

Using a parameter as a key index in JavaScript

Here's the structure of my Object festivals: Object {friday: Object} friday: Object amazon: Object band: Object Next, I've created a function called`newAct`: function newAct(band, date, startTime, endTime, stage){ var ...

TypeScript: Retrieve the data type of the provided object

Is there a way to create a function that receives a callback and returns the object returned by that callback? Here's an example of what I'm trying to achieve: const my_object = my_function<A extends string, B extends boolean> ("my_o ...

Having trouble correctly displaying a form with nested form array within a form group

I am working with a form group that contains nested form groups and a form array: ngOnInit() { this.form = this.fb.group({ dropDownOptions: this.fb.group({ items: this.fb.array([this.createItem()]) }) ...

Get the minimum value from an array that is dynamically generated using PHP

I have encountered an issue with a Wordpress shopping theme where the product details are displayed as json scripts, but I specifically need to display the price in text format. Unfortunately, due to my limited PHP knowledge and unhelpful developer, I am u ...

A guide on activating the <b-overlay> component when a child triggers an Axios request in vue.js

Is there a way to automatically activate the Bootstrap-vue overlay when any child element makes a request, such as using axios? I am looking for a solution that will trigger the overlay without manual intervention. <b-overlay> <child> ...

How can I restrict the return type of a generic method in TypeScript based on the argument type?

How can we constrain the return type of getStreamFor$(item: Item) based on the parameter type Item? The desired outcome is: When calling getStream$(Item.Car), the type of stream$ should be Observable<CarModel> When calling getStream$(Item.Animal), ...

Port 4200 is currently being utilized. Please utilize the '--port' option to designate an alternative port

Hi there, I am currently running an Angular 2 app with Express as the backend and encountering the following issue: [3] Port 4200 is already in use. Use '--port' to specify a different port. [3] [nodemon] app crashed - waiting for file changes b ...

Tips for patiently anticipating the outcome of asynchronous procedures?

I have the given code snippet: async function seedDb() { let users: Array<Users> = [ ... ]; applications.map(async (user) => await prisma.user.upsert( { create: user, update: {}, where: { id: user.id } })); } async function main() { aw ...

PHP array multiplication of digits

I've encountered an issue with my array - despite attempting to double it, the values remain unchanged. How can I rectify this situation with minimal adjustments? <?php $arr = array(1, 2, 3, 4); foreach ($arr as &$value) { $value = $val ...

The Angular Material Theme is not being properly displayed on the mtx-datetimepicker component

Issue: While using directives from ng-matero for DateTime with Angular Material for application design, the dateTimepicker element is not applying the angular material theme as desired. https://i.sstatic.net/zPBp3.png Code Example The app.module.ts file i ...

Showing content based on the route - Angular

I'm struggling to hide the navbar based on a specific route in my application. I have managed to subscribe to the route changes, but I am having difficulty changing the display property accordingly. Here is what I have so far: export class AppCompo ...

Angular 2: Emptying input field value on click event

I am experiencing an issue with resetting my input values. I have a search bar with filter functions. When I enter a value, it displays a list below and I want to add a function to these links. When I click on one of them, it takes me to another component ...

Issues arise when Typescript fails to convert an image URL into a base64 encoded string

My current challenge involves converting an image to base 64 format using its URL. This is the method I am currently using: convertToBase64(img) { var canvas = document.createElement("canvas"); canvas.width = img.width; canvas.height = img.he ...