Skip to content

Commit

Permalink
add downloaders name to metadata of datagrid export
Browse files Browse the repository at this point in the history
  • Loading branch information
qu-bit1 committed Feb 10, 2024
1 parent 5c7303c commit 8c3436f
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 2 deletions.
29 changes: 29 additions & 0 deletions components/DataGrid/excelUtils.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import ExcelJS from "exceljs";
import { saveAs } from "file-saver";

function downloadExcel(rows, columns, name, rcname) {
const wb = new ExcelJS.Workbook();
wb.creator = name;
wb.lastModifiedBy = name;
wb.created = new Date();
wb.lastPrinted = new Date();
wb.modified = new Date();
const ws = wb.addWorksheet("Sheet 1");

const headers = columns.map((column) => column.headerName);
ws.addRow(headers);

rows.forEach((row) => {
const rowData = columns.map((column) => {
const { field } = column;
return row[field] || "";
});
ws.addRow(rowData);
});

wb.xlsx.writeBuffer().then((excelBuffer) => {
saveAs(new Blob([excelBuffer]), `${rcname}.xlsx`);
});
}

export default downloadExcel;
28 changes: 26 additions & 2 deletions components/DataGrid/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,20 @@ import {
GridCellParams,
GridColDef,
// GridRowHeightParams,
GridToolbar,
GridToolbarColumnsButton,
GridToolbarContainer,
GridToolbarFilterButton,
MuiEvent,
} from "@mui/x-data-grid";
import Button from "@mui/material/Button";
import Image from "next/image";
import * as React from "react";
import { useState } from "react";
import DownloadIcon from "@mui/icons-material/Download";

import useStore from "@store/store";

import downloadExcel from "./excelUtils";

const StyledGridOverlay = styled("div")(({ theme }) => ({
display: "flex",
Expand Down Expand Up @@ -45,6 +53,16 @@ function CustomNoRowsOverlay() {
</StyledGridOverlay>
);
}

function CustomToolbar({ handleDownload }: { handleDownload: () => void }) {
return (
<GridToolbarContainer>
<GridToolbarColumnsButton />
<GridToolbarFilterButton />
<Button startIcon={<DownloadIcon />} onClick={handleDownload} />
</GridToolbarContainer>
);
}
interface paramsType {
rows: any[];
columns: GridColDef[];
Expand All @@ -69,6 +87,11 @@ function Index({
heighted = false,
}: paramsType) {
const [pageSize, setPageSize] = useState<number>(25);
const { name, rcName } = useStore();

const handleDownload = () => {
downloadExcel(rows, columns, name, rcName);
};

const cols = columns.map((col) => ({
...col,
Expand All @@ -82,7 +105,8 @@ function Index({
rows={rows}
columns={cols}
components={{
Toolbar: GridToolbar,
// eslint-disable-next-line react/no-unstable-nested-components
Toolbar: () => <CustomToolbar handleDownload={handleDownload} />,
NoRowsOverlay: CustomNoRowsOverlay,
}}
componentsProps={{
Expand Down

0 comments on commit 8c3436f

Please sign in to comment.