-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathcsv_generator.js
61 lines (51 loc) · 1.83 KB
/
csv_generator.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
49
50
51
52
53
54
55
56
57
58
59
60
61
function CsvGenerator(dataArray, fileName, separator, addQuotes) {
this.dataArray = dataArray;
this.fileName = fileName;
this.separator = separator || ',';
this.addQuotes = !!addQuotes;
if (this.addQuotes) {
this.separator = '"' + this.separator + '"';
}
this.getDownloadLink = function () {
var separator = this.separator;
var addQuotes = this.addQuotes;
var rows = this.dataArray.map(function (row) {
var rowData = row.join(separator);
if (rowData.length && addQuotes) {
return '"' + rowData + '"';
}
return rowData;
});
var type = 'data:text/csv;charset=utf-8';
var data = rows.join('\n');
if (typeof btoa === 'function') {
type += ';base64';
data = btoa(data);
} else {
data = encodeURIComponent(data);
}
return this.downloadLink = this.downloadLink || type + ',' + data;
};
this.getLinkElement = function (linkText) {
var downloadLink = this.getDownloadLink();
var fileName = this.fileName;
this.linkElement = this.linkElement || (function() {
var a = document.createElement('a');
a.innerHTML = linkText || '';
a.href = downloadLink;
a.download = fileName;
return a;
}());
return this.linkElement;
};
// call with removeAfterDownload = true if you want the link to be removed after downloading
this.download = function (removeAfterDownload) {
var linkElement = this.getLinkElement();
linkElement.style.display = 'none';
document.body.appendChild(linkElement);
linkElement.click();
if (removeAfterDownload) {
document.body.removeChild(linkElement);
}
};
}