-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
exportUtils.tsx
63 lines (56 loc) · 1.8 KB
/
exportUtils.tsx
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
62
63
export function exportToCsv(gridEl: HTMLDivElement, fileName: string) {
const { head, body, foot } = getGridContent(gridEl);
const content = [...head, ...body, ...foot]
.map((cells) => cells.map(serialiseCellValue).join(','))
.join('\n');
downloadFile(fileName, new Blob([content], { type: 'text/csv;charset=utf-8;' }));
}
export async function exportToPdf(gridEl: HTMLDivElement, fileName: string) {
const { head, body, foot } = getGridContent(gridEl);
const [{ jsPDF }, { default: autoTable }] = await Promise.all([
import('jspdf'),
import('jspdf-autotable')
]);
const doc = new jsPDF({
orientation: 'l',
unit: 'px'
});
autoTable(doc, {
head,
body,
foot,
horizontalPageBreak: true,
styles: { cellPadding: 1.5, fontSize: 8, cellWidth: 'wrap' },
tableWidth: 'wrap'
});
doc.save(fileName);
}
function getGridContent(gridEl: HTMLDivElement) {
return {
head: getRows('.rdg-header-row'),
body: getRows('.rdg-row:not(.rdg-summary-row)'),
foot: getRows('.rdg-summary-row')
};
function getRows(selector: string) {
return Array.from(gridEl.querySelectorAll<HTMLDivElement>(selector)).map((gridRow) => {
return Array.from(gridRow.querySelectorAll<HTMLDivElement>('.rdg-cell')).map(
(gridCell) => gridCell.innerText
);
});
}
}
function serialiseCellValue(value: unknown) {
if (typeof value === 'string') {
const formattedValue = value.replace(/"/g, '""');
return formattedValue.includes(',') ? `"${formattedValue}"` : formattedValue;
}
return value;
}
function downloadFile(fileName: string, data: Blob) {
const downloadLink = document.createElement('a');
downloadLink.download = fileName;
const url = URL.createObjectURL(data);
downloadLink.href = url;
downloadLink.click();
URL.revokeObjectURL(url);
}