Issue
Hi I'm trying to save the content of data which came from my webserver into csv file.
I'm trying this code which came from 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 the content of data doesn't save into my summary.csv
and gave me this
[object object]
. Can someone help me with this?
Solution
The first problem is that encodeURIComponent()
requires a string, and you are giving it an object, so it calls .toString()
on it, which is why you get [object Object]
.
Instead, you need to convert your data array into a CSV string yourself. If you are using D3.js you can use d3.csv.format(rows)
, which is very nice. Or you can find another JS CSV library. Or you can use the following very simplistic implementation I just wrote for you:
function csv(arr) {
var ret = [];
ret.push('"' + Object.keys(arr[0]).join('","') + '"');
for (var i = 0, len = arr.length; i < len; i++) {
var line = [];
for (var key in arr[i]) {
if (arr[i].hasOwnProperty(key)) {
line.push('"' + arr[i][key] + '"');
}
}
ret.push(line.join(','));
}
return ret.join('\n');
}
NB: This function assumes you pass it a valid array with at least one element, and all the elements are objects with exactly the same keys. If none of these assumptions are true for you, either extend my function or use a more robust third party library.
So, putting this all together, your final code would 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 that I needed to access data.results
to get the actual array of results. And I am assuming you will use my csv()
function or another similar one to convert the array into a CSV string.
Answered By - GregL
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.