-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexportToCSV.js
More file actions
38 lines (34 loc) · 1.17 KB
/
exportToCSV.js
File metadata and controls
38 lines (34 loc) · 1.17 KB
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
/**
* convert all " to '' and add ","
*/
function fenceLine(items) {
return '"' + items.map(i => i.replaceAll('"','\'\'')).join('","') + '"\r\n';
}
export async function exportCSVFile(headers, lines, fileTitle) {
let csv = fenceLine(Object.values(headers));
for (const line of lines) {
const items = [];
for (const key of Object.keys(headers)) {
const v = line[key];
items.push(v == null ? '': v + '');
}
csv += fenceLine(items);
}
var exportedFilenmae = fileTitle + '.csv' || 'export.csv';
var blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
if (navigator.msSaveBlob) { // IE 10+
navigator.msSaveBlob(blob, exportedFilenmae);
} else {
var link = document.createElement("a");
if (link.download !== undefined) { // feature detection
// Browsers that support HTML5 download attribute
var url = URL.createObjectURL(blob);
link.setAttribute("href", url);
link.setAttribute("download", exportedFilenmae);
link.style.visibility = 'hidden';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
}
}