-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcsv.js
48 lines (35 loc) · 1.03 KB
/
csv.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
function convertArrayOfObjectsToCSV(data) {
var result, ctr, keys, columnDelimiter, lineDelimiter;
if (data === null || !data.length) {
return null;
}
columnDelimiter = ',';
lineDelimiter = '\n';
keys = Object.keys(data[0]);
result = '';
result += keys.join(columnDelimiter);
result += lineDelimiter;
data.forEach(function (item) {
ctr = 0;
keys.forEach(function (key) {
if (ctr > 0) result += columnDelimiter;
result += item[key];
ctr++;
});
result += lineDelimiter;
});
return result;
}
function downloadCSV(data) {
var csv = convertArrayOfObjectsToCSV(data);
// console.warn(csv);
if (csv === null) return;
if (!csv.match(/^data:text\/csv/i)) {
csv = 'data:text/csv;charset=utf-8,' + csv;
}
console.warn(encodeURI(csv));
var link = document.createElement('a');
link.setAttribute('href', encodeURI(csv));
link.setAttribute('download', 'export.csv');
link.click();
}