-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathCSVHelper.ts
More file actions
55 lines (48 loc) · 1.74 KB
/
CSVHelper.ts
File metadata and controls
55 lines (48 loc) · 1.74 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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
export const exportToCsv = (filename: string, rows: object[], headers?: string[]): void => {
if (!rows || !rows.length) {
return;
}
const separator: string = ",";
const keys: string[] = Object.keys(rows[0]);
let columHearders: string[];
if (headers) {
columHearders = headers;
} else {
columHearders = keys;
}
const csvContent =
"sep=,\n" +
columHearders.join(separator) +
'\n' +
rows.map(row => {
return keys.map(k => {
let cell = row[k] === null || row[k] === undefined ? '' : row[k];
cell = cell instanceof Date
? cell.toLocaleString()
: cell.toString().replace(/"/g, '""');
if (navigator.msSaveBlob) {
cell = cell.replace(/[^\x00-\x7F]/g, ""); //remove non-ascii characters
}
if (cell.search(/("|,|\n)/g) >= 0) {
cell = `"${cell}"`;
}
return cell;
}).join(separator);
}).join('\n');
const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
if (navigator.msSaveBlob) { // In case of IE 10+
navigator.msSaveBlob(blob, filename);
} else {
const link = document.createElement('a');
if (link.download !== undefined) {
// Browsers that support HTML5 download attribute
const url = URL.createObjectURL(blob);
link.setAttribute('href', url);
link.setAttribute('download', filename);
link.style.visibility = 'hidden';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
}
}