-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexportUtils.tsx
91 lines (81 loc) · 2.25 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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import { cloneElement } from "react";
import type { ReactElement } from "react";
import type { DataGridProps } from "react-data-grid";
export async function exportToCsv<R, SR>(
gridElement: ReactElement<DataGridProps<R, SR>>,
fileName: string
) {
const { head, body, foot } = await getGridContent(gridElement);
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<R, SR>(
gridElement: ReactElement<DataGridProps<R, SR>>,
fileName: string
) {
const [{ jsPDF }, autoTable, { head, body, foot }] = await Promise.all([
import("jspdf"),
(await import("jspdf-autotable")).default,
await getGridContent(gridElement),
]);
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);
}
async function getGridContent<R, SR>(
gridElement: ReactElement<DataGridProps<R, SR>>
) {
const { renderToStaticMarkup } = await import("react-dom/server");
const grid = document.createElement("div");
grid.innerHTML = renderToStaticMarkup(
cloneElement(gridElement, {
enableVirtualization: false,
})
);
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(grid.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);
}