Alternate way to Add a Slick Angular CSV Download Link Reply

misc3_bgThis is a follow-up to AJ Keresztes’ post earlier this week. Check it out before going on…

AJ’s code works fine.  The only issue I had was creating the ‘csvData’ object.

I created the following object, and it simplified things:
var obj = [{ a: 11, b: 22 }, { a: 11, b: 22 }, { a: 11, b: 22 }, { a: 11, b: 22 }];
var csvData’ = exportCSV.objectToCSV(obj, ‘aaaa.csv’);    // This create the csvData list object (with the header information from the list).
exportCSV.objectToFile(obj, ‘aaaa.csv’);  // This will take the json list object, and send it out to the given filename.
 
Will create a file with the following:
a
b
11
22
11
22
11
22
11
22
 
 
————— The helper code:
/* jshint -W089 */

var exportCSV =
    {
        objectToArrayList: function (obj) {
            var list = [];
            var item = null;
            {   // Column names
                item = [];
                for (var keyTitle in obj[0]) {
                    item.push(keyTitle);
                }
                list.push(item);
            }

            for (var i = 0; i < obj.length; i++) // Row data
            {
                item = [];
                for (var key in obj[i]) {
                    item.push(obj[i][key]);}
                list.push(item);
            }
            return list;
        },
        arrayListToCSV: function (obj) {
            var list = [];
            for (var i = 0; i < obj.length; i++){
                list.push(obj[i].join('\t,'));
            }
            return list.join('\r\n');
        },
        objectToCSV: function (obj) {
            var arrayList = exportCSV.objectToArrayList(obj);
            var cSV = exportCSV.arrayListToCSV(arrayList);
            return cSV;
        },
        objectToCSVFile: function (obj, fileName) {
            var data = exportCSV.objectToCSV(obj);
            var element = angular.element('<a/>');
            element.attr({
                href: 'data:attachment/csv;charset=utf-8,' + encodeURI(data),
                target: '_blank',
                download: fileName
            })[0].click();
            return data;
        }
    };

 

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s