Issue with exporting to Excel in AngularJS in Internet Explorer not functioning as expected

Having some trouble exporting data to Excel or PDF in IE, but it works fine in Chrome. Since most users will be using Internet Explorer, can someone please review my code and provide suggestions?

Below is the Angular function I am using:

          scope.exportData = function () {
            var date = new Date();
            var d = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate();
            var blob = new Blob([document.getElementById('exportable').innerHTML], {
                type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"

            });
            saveAs(blob, "Report_" + d + ".xls");
        };

        scope.exportDataItems = function () {
            var date = new Date();
            var d = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate();
            var blob = new Blob([document.getElementById('exportablePRItems').innerHTML], {
                type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"

            });
            saveAs(blob, "Items_"+ d +".xls");
        };


    }]);

I am utilizing Blob.js.

Answer №1

To enable export to Excel, JSONCSVConverter can be utilized with the following steps:

  1. Include the JSONtoCSVConverter JavaScript file.
  2. Prepare the JSON data.
  3. Use Jquery library.

This specific line plays a crucial role: JSONToCSVConvertor(data, "Blog Report", true);

Explanation of parameters: 1st parameter - Data input 2nd parameter - File name specification 3rd parameter - Label inclusion condition

For more details and guidance, refer to the resources below:

Blog

Plunker

    <!DOCTYPE html>
<html>
<head>
    <title>Internet explorer download</title>
    <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
    <script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
</head>
<body>
    <div align="center">
        <h3><u>Enter JSON data</u></h3>
        <div class="mydiv">
    <textarea cols="100" rows="15" class="txtarea" id="txt">[{"Blog Name":"PrathapKudupusBlog","Date":"30 Jul 2013 09:24 AM","Type":"Technical","Author"
:"Prathap Kudupu"},
{"Blog Name":"ABCBlog","Date":"30 Jul 2011 09:24 AM","Type":"Technical","Author"
:"ABC"},
{"Blog Name":"XYZBlog","Date":"30 Jul 2011 09:24 AM","Type":"Technical","Author"
:"XYZ"}]</textarea>      <br>
        <h3><u>Click below button to download <strong>CSV</strong> file for internet explorer and other browsers</u></h3>
        <br>
        <button class="download">Download CSV</button>
    </div>
</body>
</html>
<script>
$(document).ready(function(){
    $('button').click(function(){
        var data = $('#txt').val();
        if(data == '')
            return;

        JSONToCSVConvertor(data, "Blog report", true);
    });
});

 function JSONToCSVConvertor(JSONData,title, ShowLabel) {
            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]) {
                    var arrValue = arrData[i][index] == null ? "" : '="' + arrData[i][index] + '"';
                    row += arrValue + ',';
                }
                row.slice(0, row.length - 1);
                CSV += row + '\r\n';
            }
            if (CSV == '') {
                growl.error("Invalid data");
                return;
            }
            var fileName = title;
            if (msieversion()) {
                var IEwindow = window.open();
                IEwindow.document.write('sep=,\r\n' + CSV);
                IEwindow.document.close();
                IEwindow.document.execCommand('SaveAs', true, fileName + ".csv");
                IEwindow.close();
            } else {
                var uri = 'data:application/csv;charset=utf-8,' + escape(CSV);
                var link = document.createElement("a");
                link.href = uri;
                link.style = "visibility:hidden";
                link.download = fileName + ".csv";
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
            }
        }
        function msieversion() {
            var ua = window.navigator.userAgent;
            var msie = ua.indexOf("MSIE ");
            if (msie != -1 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) // If Internet Explorer, return version number 
            {
                return true;
            } else { // If another browser, 
                return false;
            }

        }
</script>

Answer №3

Perhaps this information could offer some assistance. :)

  scope.exportDataNew = function () {
                var d = new Date();
                var months = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
                if (typeof scope.filter_fromDate == 'undefined') {
                    scope.filter_fromDate = months[d.getMonth()] + ' ' + d.getDate().toString() + ", " + d.getFullYear().toString();

                }
                if (typeof scope.filter_toDate == 'undefined') {
                    scope.filter_toDate = months[d.getMonth()] + ' ' + d.getDate().toString() + ", " + d.getFullYear().toString();
                }
                if (typeof scope.EntityID == 'undefined') {
                    scope.EntityID = "";
                }
                if (typeof scope.DepartmentID == 'undefined') {
                    scope.DepartmentID = "";
                }
                location.href = 'ExportExcel?from=' + scope.filter_fromDate + '&to=' + scope.filter_toDate + '&EntityID=' + scope.EntityID + '&DepartmentID=' + scope.DepartmentID;
            };
            scope.exportData = function () {
                var date = new Date();
                var d = date.getFullYear() + '-' + date.getMonth() + 1 + '-' + date.getDate();
                var blob = new Blob([document.getElementById('exportable').innerHTML], {
                    type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"

                });
                saveAs(blob, "Report_" + d + ".xls");
            };

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

Unable to properly display the message in Angular

<!DOCTYPE html> <html ng-app> <head> <script data-require="angular.js@*" data-semver="1.4.3" src="https://code.angularjs.org/1.4.3/angular.js"></script> <link rel="stylesheet" href="style.css" /> ...

Exploring the blur() function in JavaScript through cold calling

There is a specific line of code that I need help with. document.getElementById("firstName").addEventListener("blur", validateField); Additionally, there is this block of code: validateField = (event) => { const el = event.targe ...

How do I use React and Material-UI to efficiently display multiple tables from a complex JSON object containing multiple arrays of data?

Trying to come up with an innovative approach to generate a unique dynamic table component that can create individual tables based on the number of arrays in a dictionary object (essentially iterating through each array and generating a table). For my sce ...

tips for enabling communication between the server and client

As someone who is new to the world of web development, please bear with me as I ask a question out of curiosity. I am wondering if there is a method for the server to push messages to clients. For instance, imagine a client's webpage featuring a news ...

I encountered an issue while trying to send data from a React.js application to PHP using Axios. However,

I am utilizing react.js, axios, and PHP to transmit data to a MySQL database Below is my react.js code snippet sendData(){ var data = new FormData(); data.append('name', 'jessie'); data.append('time', '12:00'); dat ...

Is it possible to modify the inactive color of just one radio button in Framework7?

Is there a way to change the inactive color of only one radio button in Framework7? I am aware that using the CSS variable --f7-radio-inactive-color allows me to set the inactive color for all radio buttons. However, I specifically want to modify the inac ...

Enhance your Vue PWA by utilizing ServiceWorker to efficiently cache remote media assets fetched from an array of URLs

In my PWA development project, I am looking to provide users with the option to download and cache all media assets used in the application. However, the default behavior of PWAs only caches assets when they are requested during app navigation. My goal is ...

Managing HTTP requests across different HTML pages in a Cordova mobile application

I have developed a Multiple Page Application (MPA) for Android and iOS which navigates to different pages when users want to view them. Everything is running smoothly so far, but I now want to add some backend sync features. The issue I am facing is that I ...

Guide on incorporating a promise call within a forEach loop

angular.forEach(data.rows, function(value, key){ var cell = []; subId = 0; angular.forEach(vm.tableJson, function(value1, key1){ if(value1.Type != 'table'){ if(key == 0){ vm.columns.push(valu ...

Unable to access Bootstrap dropdown menu after initial ajax form submission

I am encountering an issue with a dropdown menu on my webpage, specifically within the manager.php file. Please excuse any formatting discrepancies as I am using Bootstrap: <!-- Bootstrap --> <script type="text/javascript" src="https://netdna ...

Implementing model synchronization on server initialization with Next.js and sequelize

When it comes to using Express with React on the backend, I'm accustomed to working in a server.js file to synchronize the database. However, I've recently started working with Next.js and noticed that there's no server.js file to sync the m ...

Having trouble with creating a new Next.js app using the latest version with npx?

Having some difficulty with the "npx create-next-app@latest" command while setting up Next.js. As a newcomer to both the community and Next.js, I could use some assistance in resolving this problem. Upon running the command, an unfamiliar message was displ ...

Sorting alphanumeric strings in React Bootstrap Table Next on a dynamic table

I am facing an issue with sorting columns in a dynamic table with over 70 columns using React-Bootstrap-Table-Next. The problem arises when trying to sort the columns in alphanumerical order, as some columns contain numbers and others contain letters. The ...

Analyzing data visualization within CSS styling

I have the desire to create something similar to this, but I am unsure of where to start. Although I have a concept in mind, I am struggling to make it functional and visually appealing. <div id="data"> <div id="men" class="shape"></di ...

Switch the view to a grid layout upon clicking

Using bootstrap 5, I've successfully created a list view: <div class="col"> Click to switch to grid/list </div> Below is the content list: <div class="row mt-3 list"> list view ... ..... ....... </div ...

Neglecting specific packages in package-lock.json

Currently facing a perplexing dilemma with no clear solution in sight. In our ongoing project, we rely on npm for package management. Although we haven't been utilizing package-lock.json file lately, the need to reintroduce it has emerged. The issue ...

What information is best stored in a database to uniquely identify users as their DotNetOpenAuth ClaimedIdentifier may change over time

There have been several inquiries similar to this and this all suggesting that ClaimedIdentifier is the way to uniquely identify users. Upon successful login, I save the ClaimedIndentifier in my database. However, I've noticed that the ClaimedIdentif ...

Creating a PDF from dynamic HTML and transferring it to an AWS S3 bucket without the need to download the PDF

We have created a web application using React JS where we attempted to generate a PDF. Instead of downloading or opening the PDF in a new window, our goal is to directly upload it to an AWS S3 bucket. We have researched and tried various samples but have n ...

The search function in Typeahead is not activating the API request while typing

Having some trouble implementing a typeahead search feature in my nodejs application with mysql. I can't seem to figure out what's wrong with my code. When I manually access http://localhost:5000/search?key=s, I'm able to see the results an ...

Sails JS - Flash message display issue on Heroku in production environment, works smoothly in development mode

I'm experiencing an issue with the flash message on my local machine during development, as it works fine there but not when I deploy the app on Heroku. I've been searching for a solution without any luck so far. api/policies/flash.js module.ex ...