Saving the content of data into csv - AngularJS -
hi i'm trying save content of data came webserver csv file.
i'm trying code came various question here in stackoverflow.
.success(function(data, status, headers, config) { console.log(data); if (data.success) { console.log(data); var saving = document.createelement('a'); saving.href = 'data:attachment/csv,' + encodeuricomponent(data); saving.download = 'summary.csv'; saving.click(); } }) .error(function(data, status, headers, config) { console.log('error in downloading!'); }); but content of data doesn't save summary.csv , gave me [object object]. can me this?
the first problem encodeuricomponent() requires string, , giving object, calls .tostring() on it, why [object object].
instead, need convert data array csv string yourself. if using d3.js can use d3.csv.format(rows), nice. or can find js csv library. or can use following simplistic implementation wrote you:
function csv(arr) { var ret = []; ret.push('"' + object.keys(arr[0]).join('","') + '"'); (var = 0, len = arr.length; < len; i++) { var line = []; (var key in arr[i]) { if (arr[i].hasownproperty(key)) { line.push('"' + arr[i][key] + '"'); } } ret.push(line.join(',')); } return ret.join('\n'); } nb: function assumes pass valid array @ least 1 element, , elements objects exactly same keys. if none of these assumptions true you, either extend function or use more robust third party library.
so, putting together, final code be:
.success(function(data, status, headers, config) { console.log(data); if (data.success) { console.log(data); var saving = document.createelement('a'); saving.href = 'data:attachment/csv,' + encodeuricomponent(csv(data.results)); saving.download = 'summary.csv'; saving.click(); } }) .error(function(data, status, headers, config) { console.log('error in downloading!'); }); note needed access data.results actual array of results. , assuming use csv() function or similar 1 convert array csv string.
Comments
Post a Comment