Alternate way to Add a Slick Angular CSV Download Link
This 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;
}
};