Storing an Excel file with JavaScript: A comprehensive guide

I've been struggling to save an Excel file using Javascript, but I'm facing compatibility issues with different browsers. I initially tried using BASE64 along with data URL, which worked well in Chrome and Firefox but failed in IE and Safari.

newlink = document.createElement('a');
newlink.setAttribute('href', 'data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,' + response.data);
newlink.setAttribute('download', 'test.xlsx');
newlink.click();

I also experimented with the Blob method, but it seems to have trouble handling binary files like PDFs, Excels, and MS Word documents.

var report = response;
var str = atob(report.data);
var blob = new Blob([str], { type: report.type});
saveAs(blob, 'report.csv');

This approach works fine for CSV files, but when trying the same with Excel or Word files, the downloaded file becomes corrupted.

I am using AngularJS for REST calls and implementing token authentication through headers. Simply opening a URL won't work due to authorization restrictions. I have tried both $resource and $http methods with no success. Interestingly, the REST API functions properly because when I access the URL directly in my browser without authentication, the file downloads correctly. The issue seems to arise during Blob creation.

If anyone has solutions or suggestions on how to resolve this dilemma, your input would be greatly appreciated.

Answer №1

Here is my current method:

To convert the array into a CSV, use the following function. This has been tested on both IE and Chrome.

exportToCsv("export.csv",arr);

function exportToCsv(filename, rows) {
    var processRow = function (row) {
        var finalVal = '';
        for (var j = 0; j < row.length; j++) {
            var innerValue = row[j] === null ? '' : row[j].toString();
            if (row[j] instanceof Date) {
                innerValue = row[j].toLocaleString();
            };
            var result = innerValue.replace(/"/g, '""');
            if (result.search(/("|,|\n)/g) >= 0)
                result = '"' + result + '"';
            if (j > 0)
                finalVal += ',';
            finalVal += result;
        }
        return finalVal + '\n';
    };

    var csvFile = '';
    for (var i = 0; i < rows.length; i++) {
        csvFile += processRow(rows[i]);
    }

    var blob = new Blob([csvFile], { type: 'text/csv;charset=utf-8;' });
    if (navigator.msSaveBlob) { // IE 10+
        navigator.msSaveBlob(blob, filename);
    } else {
        var link = document.createElement("a");
        if (link.download !== undefined) { // feature detection
            // Browsers that support HTML5 download attribute
            var url = URL.createObjectURL(blob);
            link.setAttribute("href", url);
            link.setAttribute("download", filename);
            link.style = "visibility:hidden";
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }
    }
}

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

Showing JSON Array Values in a Table

I have created an array and am attempting to display its values in a table. Initially, my solution only displayed a single value from the array that matched an exact ID. You can see this implementation at (). Entering "jjones" would yield a result. I then ...

Relocating sprite graphic to designated location

I am currently immersed in creating a captivating fish animation. My fish sprite is dynamically moving around the canvas, adding a sense of life to the scene. However, my next goal is to introduce food items for the fishes to feast on within the canvas. Un ...

The background image fails to show up on the mobile device display

Currently, I am working on an app with Ionic, but unfortunately, the background image is not showing despite all my efforts. I have gone through various solutions provided in previous questions, but none of them seem to work for me. Here is the CSS I am u ...

Tips for including a hashtag in an AJAX request

When using ajax to send messages to the server in my chat application, I encountered an issue where everything after a hashtag is omitted. I attempted to address this by encoding the message, but it resulted in other complications in the PHP code. The enco ...

Show the cell data when the checkbox next to it is selected

I have a specific table setup and I am trying to display the content of the table cell if its corresponding checkbox is checked upon clicking a button. For example: If Row2 is checked, an alert box should display Row2 Below is my code snippet, Java ...

How can I adjust the transparency in a JavaScript popup modal window for an ASP.Net GridView?

Recently, I added an 'onclick' event to every row of an asp gridview and the popup window that appears is functioning perfectly. Now, I'm interested in adding a transparency level to the body of the popup window for a translucent effect. Can ...

Is there an issue with $scope variable overriding on ng-blur? The ng-model isn't updating with the $scope variable in

I am currently developing a web app using ionic/angular where users have the option to select a location either from a Google map displayed in a modal or through a Google Map autocomplete searchbox. To enhance the user experience, I want the address chose ...

How do I connect to a different application's view?

When working with a view that has tiles, I am looking to click on one of them and be directed to a different application that I have created. In typical cases, I would specify the view folder for navigation. However, when attempting something similar for ...

Guidance on sharing an image on Twitter using Node.js

Every time I attempt to upload a PNG image to the Twit library in Node, an error arises. My objective is to develop a Twitter bot in Node.js that generates a random RGB colour, creates an image of this colour, and tweets it. Thanks to some assistance prov ...

Leveraging an external global variable file that is not incorporated into the bundle

I have a JavaScript file dedicated to internationalization. I am looking for a way to provide this file to clients for them to edit without requiring me to rebuild the entire project. Currently, I store this file in the static folder so it is included in ...

Enhance the textarea using Javascript when clicked

I am experimenting with styling my textarea using a combination of JAVASCRIPT and CSS. The goal is to make it expand in size from 20px height to 120px height when clicked, using document.getElementById("tweet_area"). However, I am facing an issue where t ...

Creating an HTTPS server that can be accessed via my specific IP address

My attempt to create ad hoc and OpenSSL based certificates in Python Flask was inspired by a tutorial I found on this website. I also explored the method of creating root CA, trusting it, and generating certificates as outlined on this GitHub thread using ...

Twice the calls are being made by jQuery Ajax

I am using an <input> tag with the following attributes: <input type="button" id="btnSave2" value="Save" onclick="Event(1)" class="btn btn-primary col-lg-12" /> In addition, I have a script as ...

I am having trouble passing a variable into the AJAX URL using JavaScript

Currently, I am attempting to remove an item from mongodb. However, I am encountering difficulty passing the id into the URL through the ajax call. Below is my code: $(".delete-item").on('click', function(e, id) { var deleteName = ...

Utilizing Electron's <webview> feature to display push notification count in the title

I'm currently working on a Windows app using Electron's webViewTag to integrate WhatsApp Web. While I have successfully implemented desktop toast notifications, I am curious if it is possible to display a notification count in the title bar of my ...

Tips for checking the validity of PHP variable names, such as $as['abc'], within an HTML textbox

Can anyone assist me with validating a user input PHP variable name such as $as_cap['abc'] during insertion? I need to verify if the format of the variable name is correct or incorrect. Currently, I am using eregi("^[a-z0-9_.'-]{1,50}$") ...

Implementing endless scrolling in AngularJS using Django REST framework

I have been exploring a tutorial on implementing infinite scrolling, which you can find here. However, I seem to be encountering an error that reads: "angular.js:38Uncaught Error: [$injector:modulerr" Could it be that I am missing something in my implem ...

What is the best way to determine which section of a promise chain is responsible for an error in Javascript?

(Please excuse any errors in my English) I am currently studying JavaScript promises. Below is a simple JavaScript code snippet for node.js (using node.js version v10.0.0) that asynchronously reads and parses a JSON file using promise chaining. const fs ...

Combine the click event and onkeydown event within a single function

I have a function that sends a message when the Enter key is pressed. However, I also created a button to send a message, but when I call this function, the message doesn't send, even though I added a click event. function inputKeyDown(event, input ...

Text about the three.js orthographic camera: "Exploring the

I'm trying to implement an orthographic camera overlay for a heads-up display on top of my main camera. I'm having trouble getting any text to show up, here's the code snippet: function setupHUD() { var width = window.innerWidth; var h ...