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

Synchronizing Ionic Data Between Screen and Controller

I am new to the Ionic framework and encountering a data synchronization issue. The problem occurs when the interface calls a function on the controller, which removes an item from an array called lupulos. This array is linked with Angular's ng-repeat= ...

Suggestions for rectifying the calculation script to include the price, a phone number, 2 digits, and integrating a textfield for cost

I have developed a script that calculates prices, phone numbers, and extracts the last 2 digits from the phone number. In my website, the price is displayed through a select option. However, I am facing an issue where the cost does not automatically updat ...

What steps can be taken to avoid being logged out automatically upon clicking the back button?

Currently, my code automatically logs out of the application when the browser is closed. However, I am facing an issue where it also logs out when I press the browser's back button and navigate to another page. I would like the code to only logout au ...

Encountering a JavaScript problem in Google Chrome?

Something strange is happening when I try to place an image in the canvas... "Uncaught TypeError: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The provided value is not of type '(HTMLImageElement or HTMLVideo ...

The share-modal.js file is throwing an error because it is unable to read properties of null, particularly the 'addEventListener' property, at

I encountered an error that I want to resolve, but it's proving to be quite challenging. Despite extensive searching on Google, I haven't found a solution yet. Uncaught TypeError: Cannot read properties of null (reading 'addEventListener&apo ...

React with TypeScript - Troubleshooting TS Error when Iterating over List Item (LI) Elements

Iterating through a group of <li> elements to strip away a specific class, then applying the same class to a different <li>. See the snippet below: useEffect(() => { if (dnArrowIdx === undefined) { const allLi = Array.from(document. ...

Using Angular to dynamically access component properties

Seeking assistance with creating dynamic Tabs in TabView of PrimeNG. The components are displaying properly, but I am unsure how to access their properties. I am following the guidelines provided at https://angular.io/guide/dynamic-component-loader and us ...

What is the best way to determine if certain rows of data have been successfully loaded when working with Ext.data.operation and an ajaxProxy?

Here is the provided code snippet: Ext.define('Book', { extend: 'Ext.data.Model', fields: [ {name: 'id', type: 'int'}, {name: 'title', type: 'string'}, {name: &apo ...

Locating specific text within an <li> element using the provided value

So, I have this set of words: <li>name</li> <li>myname</li> <li>yourname</li> Then there's also an input box input type="text" value="name" id="the_value" with the value "name", along with a submit button identif ...

Changing the Javascript Date Object into JSON date format

I'm in the process of converting a timestamp generated by var now = new Date().getTime(); which results in the timestamp 1349916512100. I am looking to format the date as \/Date(1349916512100)\/ in order to incorporate it into a JSON st ...

Can you explain the roles of client-side and server-side in Next.js?

Could someone please elaborate on the distinction between client side and server side in Next.js as detailed in their documentation? As far as I understand, Next.js operates on React which is client side and runs in the browser, while server side refers to ...

Submitting information through Ajax

Struggling to update a field in my database using AJAX. No errors in console, but the DB won't update. Anyone able to help? AJAX: function ajaxUpdate() { var arr = {var1: name, var2: age}; $.ajax({ url: 'aja ...

inputting an array of strings into the value attribute of an input element using jQuery

Whenever a user writes something in the input field with id="clientAdd" and presses enter, that text should be displayed as a tag inside a div. These tags are then saved as an array of strings, which I want to pass as the value for the hidden input field w ...

What is the best way to perform this task in Angular2?

I am currently working with three arrays: tables = [{number:1},{number:2},{number:3},{number:4}]; foods = [ {id:1, name:'Ice Cream'}, {id:2, name:'Pizza'}, {id:1, name:'Hot Dog'}, {id:2, name:'Salad'} ]; o ...

Manipulating AngularJS variables that are outside of its designated scope should be restricted

Something strange is happening in my code. I created a function called "insertTstData" outside of any angular scope, and when it is called from another function named "save" within a controller named "remark", it somehow manipulates a local variable and th ...

Managing and keeping track of a universal value within the success callback function among numerous Ajax POST requests

I am faced with a challenge involving two HTML elements: 1). a div element that functions as a multiple select, created automatically by a predefined widget, and 2). a button that triggers an onclick event. On the JavaScript side, I have a global variable ...

Is there a way to identify modifications in the DOM using jQuery UI Sortable?

My website is built using nodejs express and mongodb, and I am interested in integrating this library. I am curious about how I can detect changes in the order of elements to save their state. Should I use a form submission or jQuery functions? For exampl ...

Why is it that this JavaScript isn't working as intended in the popup form?

</br> s_foot"> * use ajax.jquery as control event. like $("#save").click(function(){.....}); <script type="text/javascript>" var wp; var position; var pid; var product_name; var production_date; In this script, I am attempting to re ...

Whenever I try to execute the command `electron .` in the electron-quickstart project, I immediately encounter an error within the

Upon successfully installing Electron, I attempted to run it using "electron" or "electron -v" commands. Unfortunately, I encountered an error while running it on Windows 10. C:\Windows\System32\electron-quick-start>electron -v modu ...

Execute the script when the document is fully loaded

Is there a way to show a dialog in jQuery when the document loads without using <body onload="showdialog();">? Can the javascript code be placed in the main div or footer div to work like the onload event? <body onload="$('#dialog').sli ...