Exporting JSON data to CSV or XLS does not result in a saved file when using Internet Explorer

Presented below is the service I offer:

angular.module('LBTable').service('exportTable', function () {
    function JSONToCSVConvertor(JSONData, ReportTitle, ShowLabel, fileName) {
        //If JSONData isn't an object, parse the JSON string into one
        var arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData;

        var CSV = '';

        if (ShowLabel) {
            var row = "";

            for (var index in arrData[0]) {

                row += index + ',';
            }

            row = row.slice(0, -1);

            CSV += row + '\r\n';
        }

        for (var i = 0; i < arrData.length; i++) {
            var row = "";

            for (var index in arrData[i]) {
                row += '"' + arrData[i][index] + '",';
            }

            row.slice(0, row.length - 1);
            
            CSV += row + '\r\n';
        }

        if (CSV == '') {
            alert("Invalid data");
            return;
        }

document.body.removeChild(link);
    }

    return {
        exportCSV: JSONToCSVConvertor
    }
});

This service basically takes a JSON object and transforms it into a downloadable csv file.

The functionality works smoothly on Chrome and Firefox. However, in Internet Explorer (even the latest version), the file does not download and no errors appear in the console.

I am curious as to why this issue occurs. :(

(view simplified demonstration here)

Answer №1

Internet Explorer lacks support for the download attribute in an anchor tag. To work around this limitation, you can utilize a blob.

  1. Transform the JSON data into CSV format

  2. Determine the current browser using the following code snippet:

 getInternetExplorerVersion() {
            var rv = -1;
            if (navigator.appName == 'Microsoft Internet Explorer') {
                var ua = navigator.userAgent;
                var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
                if (re.exec(ua) != null)
                    rv = parseFloat(RegExp.$1);
            }
            else if (navigator.appName == 'Netscape') {
                var ua = navigator.userAgent;
                var re = new RegExp("Trident/.*rv:([0-9]{1,}[\.0-9]{0,})");
                if (re.exec(ua) != null)
                    rv = parseFloat(RegExp.$1);
            }
            return rv;
        }
  1. If the detected browser is IE
var blob = new Blob([CSV], { type: "text/csv;charset=utf-8;" });
navigator.msSaveBlob(blob, fileName + ".csv")

This method is compatible with Internet Explorer

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

How can I parse JSON responses containing lists of various types using Ktor?

In my development of an Android app, I am utilizing Ktor for handling HTTP requests to an API. The challenge I am facing involves the response containing a list that could be one of two types based on the query. Currently, I have set up four data classes - ...

The oncanplaythrough event is not functioning properly in Internet Explorer

I am facing an issue where the beep sound trigger upon receiving an API response works perfectly in Chrome and Firefox browsers, but unfortunately, it does not work in Internet Explorer. if ($scope.totalQueueList) { var audio = new Audio(); audio.s ...

Tips for retrieving JSON data using Backbone.js

I'm experimenting with using backbones.js fetch to retrieve json from a twitter search and I need some help figuring out what's wrong with my code below. Can someone lend me a hand? (function($){ var Item = Backbone.Model.extend(); var Li ...

Unable to resize react-split-pane dimensions

I recently integrated the react-split-pane plugin into my project, but I am encountering some issues with its functionality. Even though I have tested react-split-pane versions 0.1.68, 0.1.66, and 0.1.64, none of them seem to work as expected in my applic ...

Struggling to troubleshoot an error - Invalid key Token '{' found at column 2

I am encountering a debugging issue that I can't seem to resolve. form-field.html <div class='row form-group' ng-form="{{field}}" ng-class="{ 'has-error': {{field}}.$dirty && {{field}}.$invalid }"> <label cla ...

Creating a dynamic CSS height for a div in Angular CLI V12 with variables

Exploring Angular development is a new venture for me, and I could use some guidance on how to achieve a variable CSS height in Angular CLI V12. Let me simplify my query by presenting it as follows: I have three boxes displayed below. Visual representatio ...

The creation of a parameterized function that doubles as an object property

interface item { first: string; last: string; } const itemList = Item[]; updateAttribute = (index, attributeToUpdate) => { itemList[index].attributeToUpdate = "New first/last" } The snippet above showcases an interface named item with propertie ...

Why am I unable to access the array once the loop has finished?

While utilizing the Google Maps API and AngularJS (1.5.8), I encountered an issue where I couldn't access markers that were created in a loop. The code snippet below is located inside the initMap function: var markers = []; for(var i=0; i<10; i++ ...

The 'propTypes' property is not found on the 'typeof TextInput' type declaration

Trying my hand at creating a react-native component using Typescript for the first time, but I ran into an issue on line 51: Property 'propTypes' does not exist on type 'typeof TextInput Couldn't find any helpful information on similar ...

Removing the hash symbol in Angular: A step-by-step guide

My experience with AngularJS is new, and I am currently working on removing the # from the URLs without utilizing NODE or Express. The project is being hosted locally on MAMP, with index.html acting as the main entry point. Within the structure, there are ...

Tips for iterating through JSON Data:

Struggling with looping through JSON data retrieved from an ashx page to add values to li's in a ul. How can I effectively loop through and extract the values from the following JSON data? The format of the returned data looks like this: {"ImageCol ...

When you duplicate the React State object and make changes to the copied object, it directly affects

When attempting to duplicate a state object, I noticed that the state object is being modified directly in the code snippet below: @boundMethod private _onClickDeleteAttachment(attachmentName: string): void { console.log("_onClickDeleteAttachment | th ...

AngularJS $http.post() response function not executing in the correct sequence

When calling a function from my angular controller to make a $http.post() request, the code below the function call is executing before the successFunction(), preventing the code inside the if block from running. How can I ensure the if block executes wi ...

"Creating a model object for Imgur JSON data in Swift: A step-by-step guide

The structure of an Imgur image search response is as follows (simplified): { "data": [ {"title" : "Kittens", "images" : [ { "title" : "", "des ...

"Resolving the problem of converting JSON to a C# class with integer class name

Received a JSON response with the following structure: { "serp": { "1": { "href": "href1.com", "url": "url1.com" }, "2": { "href": "href2.com", "url": "url2.com" ...

Tips for storing a JavaScript variable or logging it to a file

Currently working with node, I have a script that requests data from an API and formats it into JSON required for dynamo. Each day generates around 23000 records which I am trying to save on my hard drive. Could someone advise me on how to save the conte ...

What is the best way to transmit data through a web socket connection effectively?

When it comes to sending data over a web socket connection, is there an optimal method? In my specific scenario, I am transmitting data from a C# application to a Python (Tornado) web server by sending a string with multiple elements separated by commas. I ...

Utilize the browser's back button when navigating pages that have been loaded through Ajax technology

$(document).ready(function () { $('#gnav a').click(function (e) { e.preventDefault(); $('#contents').load(this.hash.substr(1) +'.php') }); }); Here is the jQuery code I have written to load content into a ...

What are some alternative ways to refactor my code in AsyncTask without using runOnUiThread?

Greetings to all Android developers! I am facing an issue with the compatibility of my old code and API 18. All the codes below work perfectly on Android 2.3. However, when I attempt to run them on a newer API version, it results in a crash. Is there a w ...

Using JWPlayer 6 and JWPlayer 7 simultaneously in one project - how is it done?

Trying to incorporate both JWPlayer 6 and JWPlayer 7 into my expressJS, AngularJS project has been a challenge. While they each work independently without issue, bringing them together has proven to be tricky. In my index.html file, I include them separat ...