37 lines
1.1 KiB
TypeScript
37 lines
1.1 KiB
TypeScript
import * as XLSX from "xlsx";
|
|
export type FileType = "csv" | "xls" | "xlsx";
|
|
import { saveAs } from "file-saver";
|
|
import { GridColDef } from "@mui/x-data-grid";
|
|
|
|
export const exportData = <TRow, TColumn extends GridColDef>(
|
|
rows: TRow[],
|
|
columns: TColumn[],
|
|
fileType: FileType = "csv",
|
|
onlyCurrentTable = false,
|
|
setOpen: (open: boolean) => void
|
|
) => {
|
|
const exportRows = onlyCurrentTable ? rows.slice(0, 5) : rows;
|
|
const exportData = [
|
|
columns.map(col => col.headerName),
|
|
...exportRows.map(row =>
|
|
columns.map(col => (row as Record<string, unknown>)[col.field] ?? "")
|
|
),
|
|
];
|
|
|
|
const worksheet = XLSX.utils.aoa_to_sheet(exportData);
|
|
const workbook = XLSX.utils.book_new();
|
|
XLSX.utils.book_append_sheet(workbook, worksheet, "Transactions");
|
|
|
|
if (fileType === "csv") {
|
|
const csv = XLSX.utils.sheet_to_csv(worksheet);
|
|
const blob = new Blob([csv], { type: "text/csv;charset=utf-8;" });
|
|
saveAs(blob, "transactions.csv");
|
|
} else {
|
|
XLSX.writeFile(workbook, `transactions.${fileType}`, {
|
|
bookType: fileType,
|
|
});
|
|
}
|
|
|
|
setOpen(false);
|
|
};
|