The process of converting a response into an Excel file

After sending a request to the server and receiving a response, I am struggling with converting this response into an Excel file.

Response header:

Connection →keep-alive
cache-control →no-cache, no-store, max-age=0, must-revalidate
content-disposition →attachment; filename=demo.xls
content-length →7680
content-type →application/vnd.ms-excel
date →Wed, 19 Sep 2018 14:40:47 GMT
expires →0
pragma →no-cache
server →Apache
x-content-type-options →nosniff
x-frame-options →DENY
x-xss-protection →1; mode=block

Response data:

ࡱ; RootEntryWorkbook A\pmidadm Ba==h:#8X@"1Arial1Arial1Arial1Arial1Calibri1Calibri1Calibri"$"#,##0_);("$"#,##0)"$"#,##0_);Red "$"#,##0.00_);(* "-"??);(@) #.##0 #,##0.000[$-1009]mmmm d, yyyy;@_($*

,##0.00_)

+ ) , * ! " # # ! # # `Demo

Here is what I tried:

var blob = new Blob([result.data], 
      {
        'type': 'application/vnd.ms-excel',
      }    
)
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = 'demo.xls';
document.body.appendChild(link);

link.click();

Unfortunately, when attempting to open the file, I encountered an error and it failed to open correctly.

Any assistance or guidance would be greatly appreciated. Thank you.

Answer №1

Retrieve the server response and convert it into an array buffer. Then, save it as a Blob with the appropriate content type obtained from the server (usually application/vnd.openxmlformats-officedocument.spreadsheetml.sheet):

var httpPromise = this.$http.post(server, postData, { responseType: 'arraybuffer' });
httpPromise.then(response => this.save(new Blob([response.data],
    { type: response.headers('Content-Type') }), fileName));

Proceed to store the blob on the user's device:

save(blob, fileName) {
    if (window.navigator.msSaveOrOpenBlob) { // Specifically for IE:
        navigator.msSaveBlob(blob, fileName);
    } else { // For other browsers:
        var link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        link.download = fileName;
        link.click();
        window.URL.revokeObjectURL(link.href);
    }
}

Reference

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

Using an AngularJS directive to trigger a function with ng-click

Everything is working well with my directive, but I would like to utilize it within ng-click. Unfortunately, the function inside the link is not getting triggered. Here's the link to the code snippet. <div ng-app="editer" ng-controller="myCtrl" ...

PHP Foreach Loop doesn't execute JavaScript Sum Function as expected

Currently, I have a JavaScript function implemented that utilizes the IDs of 3 textboxes to retrieve their numeric values, sum them together, and display the result in the fourth textbox. In addition, I am fetching a list of individuals from my database an ...

Tips on integrating a series of typical utility directives into an Angular module

If we have a collection of versatile angular directives, such as one that ignores non-numeric characters when typed, how can we best organize and include them in our Angular modules? Should we create a separate module, like Foo, to house these directives? ...

Is the variable not being initialized outside of the function?

I'm really struggling with this async issue. I can't seem to get it to work because the summonerData array is not being set. I have a feeling it has something to do with async, but I'm not sure how to troubleshoot it. var summonerName = req ...

Adding a space after a comma automatically upon saving changes in VSCode

Whenever I input code (t,s) into the system and make changes to it, it automatically transforms into (t, s) with an added space after the comma. Is there a way to avoid VScode from adding this extra space on its own? ...

Is it possible to manipulate videos embedded in an iframe using javascript?

It's common knowledge that JavaScript commands from Google can be used to control YouTube videos, while Vimeo provides its own JavaScript commands for their videos. Both videos are typically embedded within 'iframes' on websites. I'm ...

React does not allow _id to be used as a unique key

When I retrieve the categories from my allProducts array fetched from the database using redux-toolkit, I filter and then slice the array for pagination before mapping over it. However, I keep encountering a warning: Each child in a list should have a un ...

In order to locate a matching element within an array in a JSON file and update it, you can use Node

Good day, I have a script that updates the value in a JSON file const fsp = require('fs').promises; async function modifyNumberInFile() { try { let data = await fsp.readFile('example.json'); let obj = JSON.parse(dat ...

angular2 with selenium webdriver: Issue with resolving 'child_process' conflict

I followed these steps: ng new typescript-selenium-example npm install selenium-webdriver --save I also made sure to copy chromedriver to my /Application. I updated the app.component.ts file as shown below: import { Component } from '@angular/core ...

How can we stop the jumping of images in the grid? Is there a way to eliminate the jump effect?

Here is a script I am working with: <script src="http://static.tumblr.com/mviqmwg/XyYn59y3a/jquery.photoset-grid.min.js"></script> <script> $(document).ready(function() { $('.photoset-grid').photose ...

Oops! There was an issue trying to solve the command "/bin/bash -ol pipefail -c npm run build" while deploying a Next.js app on Railway. Unfortunately, it did not complete successfully and returned an exit code of

[stage-0 8/10] RUN --mount=type=cache,id=s/8a557944-4c41-4e06-8de9-06bfcc5e8aaf-next/cache,target=/app/.next/cache --mount=type=cache,id=s/8a557944-4c41-4e06-8de9-06bfcc5e8aaf-node_modules/cache,target=/app/node_modules/.cache npm run build: 17.62 17.62 ...

Testing controllers in AngularJS with units

Unit testing in AngularJs has been a bit confusing for me as I am just getting started with it. The syntax seems unusual to me, especially when writing tests for a controller. Here is an example code snippet: describe('PhoneCat controllers', fun ...

I am currently studying JavaScript. The syntax of my if statement with && appears to be accurate, however

I'm having trouble with the logic in my "Code your Own Adventure" program on Code Academy. I expect it to display "Great, come get your pizza!" when I enter PIZZA, YES, and YES as prompts, but instead it says "NO pizza for you!" I've tried using ...

Generating instances using TypeScript generics

Looking to create a factory for instantiating classes with generics. After checking out the TypeScript docs, everything seems to work as expected. Here's a simplified version of how it can be done: class Person { firstName = 'John'; ...

Issue with retrieving data using AngularJS Restangular

I've been trying to figure out how to make restangular work properly. When I call my API (using the endpoint /user) I receive the following JSON response: { "error": false, "response": { "totalcount": 2, "records": [{ "id": "1", ...

Storing files offline in Firefox 3.5 with file:// protocol

While experimenting with the code for offline storage in Firefox 3.5, I referred to a tutorial on . When the page loads, I am prompted with a dialog asking to store data, but after clicking Allow, the dialog does not disappear. The application functions co ...

What measures can be taken to ensure that the input checkbox is not toggled by accidentally pressing

There's a checkbox input in a dropdown menu at the top of the page that is giving me some trouble. When I select an option by clicking on it, for some reason pressing the spacebar toggles it off and on. Clicking outside once doesn't correct it, I ...

Determine whether the function name in a given string matches a JavaScript or PHP

I am currently attempting to highlight code and eventually sanitize the HTML, but I am encountering an issue with my regex not matching just the function name and parameters. Regex is not my strong suit and can be quite confusing for me. Additionally, when ...

When attempting to send emails, SendGrid encounters an error and fails to provide an error code

Earlier today, I successfully sent out a series of emails using SendGrid. It was quite a large number of emails, as I needed to create multiple user accounts with attached email addresses. Thankfully, everything went smoothly and all the emails were delive ...

Finding the maximum value among multiple variables in AngularJS

After performing calculations, I have assigned specific values to variables. console.log("Gain_weight is "+ Gain_weight); console.log("Gain_smoking is "+ Gain_smoking); console.log("Gain_exercising is "+ Gain_exercising); console.log("Gain_foodhabits ...