38 lines
1.1 KiB
TypeScript
38 lines
1.1 KiB
TypeScript
import * as XLSX from "xlsx";
|
|
import { GridColDef } from "@mui/x-data-grid";
|
|
export type FileType = "csv" | "xls" | "xlsx";
|
|
import { saveAs } from "file-saver";
|
|
|
|
import type { ITransaction } from "../features/Pages/Transactions/types";
|
|
|
|
|
|
export const exportData = (
|
|
transactions: ITransaction[],
|
|
columns: GridColDef[],
|
|
fileType: FileType = "csv",
|
|
onlyCurrentTable = false,
|
|
setOpen: (open: boolean) => void
|
|
) => {
|
|
const exportRows = onlyCurrentTable ? transactions.slice(0, 5) : transactions;
|
|
const exportData = [
|
|
columns.map((col) => col.headerName),
|
|
...exportRows.map((row) => columns.map((col) => row[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);
|
|
};
|