Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[DataGridPremium] Add excel export #3802

Closed
wants to merge 21 commits into from
Closed
Show file tree
Hide file tree
Changes from 11 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions docs/pages/api-docs/data-grid/grid-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import { GridApi } from '@mui/x-data-grid-pro';
| <span class="prop-name">commitRowChange</span> | <span class="prop-type">(id: GridRowId, event?: MuiBaseEvent) =&gt; boolean \| Promise&lt;boolean&gt;</span> | Updates the row at the given id with the values stored in the edit row model. |
| <span class="prop-name">deleteFilterItem</span> | <span class="prop-type">(item: GridFilterItem) =&gt; void</span> | Deletes a [GridFilterItem](/api/data-grid/grid-filter-item/). |
| <span class="prop-name">exportDataAsCsv</span> | <span class="prop-type">(options?: GridCsvExportOptions) =&gt; void</span> | Downloads and exports a CSV of the grid's data. |
| <span class="prop-name">exportDataAsExcel</span> | <span class="prop-type">(options?: GridExcelExportOptions) =&gt; void</span> | Downloads and exports a excel of the grid's data. |
| <span class="prop-name">exportDataAsPrint</span> | <span class="prop-type">(options?: GridPrintExportOptions) =&gt; void</span> | Print the grid's data. |
| <span class="prop-name">forceUpdate</span> | <span class="prop-type">() =&gt; void</span> | Forces the grid to rerender. It's often used after a state update. |
| <span class="prop-name">getAllColumns</span> | <span class="prop-type">() =&gt; GridStateColDef[]</span> | Returns an array of [GridColDef](/api/data-grid/grid-col-def/) containing all the column definitions. |
Expand All @@ -33,6 +34,7 @@ import { GridApi } from '@mui/x-data-grid-pro';
| <span class="prop-name">getColumnPosition</span> | <span class="prop-type">(field: string) =&gt; number</span> | Returns the left-position of a column relative to the inner border of the grid. |
| <span class="prop-name">getColumnsMeta</span> | <span class="prop-type">() =&gt; GridColumnsMeta</span> | Returns the GridColumnsMeta for each column. |
| <span class="prop-name">getDataAsCsv</span> | <span class="prop-type">(options?: GridCsvExportOptions) =&gt; string</span> | Returns the grid data as a CSV string.<br />This method is used internally by `exportDataAsCsv`. |
| <span class="prop-name">getDataAsExcel</span> | <span class="prop-type">(options?: GridExcelExportOptions) =&gt; Promise&lt;Workbook&gt;</span> | Returns the grid data as an exceljs workbook.<br />This method is used internally by `exportDataAsExcel`. |
| <span class="prop-name">getEditRowsModel</span> | <span class="prop-type">() =&gt; GridEditRowsModel</span> | Gets the edit rows model of the grid. |
| <span class="prop-name">getLocaleText</span> | <span class="prop-type">&lt;T extends GridTranslationKeys&gt;(key: T) =&gt; GridLocaleText[T]</span> | Returns the translation for the `key`. |
| <span class="prop-name">getPinnedColumns</span> | <span class="prop-type">() =&gt; GridPinnedColumns</span> | Returns which columns are pinned. |
Expand Down
36 changes: 36 additions & 0 deletions docs/src/pages/components/data-grid/export/ExcelExport.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import * as React from 'react';
import {
DataGridPro,
GridToolbarContainer,
GridToolbarExport,
} from '@mui/x-data-grid-pro';
import { useDemoData } from '@mui/x-data-grid-generator';

function CustomToolbar() {
return (
<GridToolbarContainer>
<GridToolbarExport />
</GridToolbarContainer>
);
}

export default function ExcelExport() {
const { data, loading } = useDemoData({
dataSet: 'Commodity',
rowLength: 4,
maxColumns: 6,
});

return (
<div style={{ height: 300, width: '100%' }}>
<DataGridPro
{...data}
loading={loading}
components={{
Toolbar: CustomToolbar,
}}
experimentalFeatures={{ excelExport: true }}
/>
</div>
);
}
36 changes: 36 additions & 0 deletions docs/src/pages/components/data-grid/export/ExcelExport.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import * as React from 'react';
import {
DataGridPro,
GridToolbarContainer,
GridToolbarExport,
} from '@mui/x-data-grid-pro';
import { useDemoData } from '@mui/x-data-grid-generator';

function CustomToolbar() {
return (
<GridToolbarContainer>
<GridToolbarExport />
</GridToolbarContainer>
);
}

export default function ExcelExport() {
const { data, loading } = useDemoData({
dataSet: 'Commodity',
rowLength: 4,
maxColumns: 6,
});

return (
<div style={{ height: 300, width: '100%' }}>
<DataGridPro
{...data}
loading={loading}
components={{
Toolbar: CustomToolbar,
}}
experimentalFeatures={{ excelExport: true }}
/>
</div>
);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<DataGridPro
{...data}
loading={loading}
components={{
Toolbar: CustomToolbar,
}}
experimentalFeatures={{ excelExport: true }}
/>
2 changes: 2 additions & 0 deletions docs/src/pages/components/data-grid/export/export.md
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,8 @@ You can remove the Print export option from the toolbar by setting `disableToolb

## 🚧 Excel export [<span class="plan-premium"></span>](https://mui.com/store/items/material-ui-pro/)

{{"demo": "pages/components/data-grid/export/ExcelExport.js", "bg": "inline"}}

> ⚠️ This feature isn't implemented yet. It's coming.
>
> 👍 Upvote [issue #198](https://github.com/mui-org/material-ui-x/issues/198) if you want to see it land faster.
Expand Down
5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -78,11 +78,11 @@
"@emotion/styled": "^11.6.0",
"@eps1lon/enzyme-adapter-react-17": "^0.1.0",
"@mui/icons-material": "^5.3.1",
"@mui/monorepo": "https://github.com/mui-org/material-ui.git#master",
"@mui/material": "^5.3.1",
"@mui/monorepo": "https://github.com/mui-org/material-ui.git#master",
"@mui/utils": "^5.3.0",
"@playwright/test": "1.17.1",
"@octokit/rest": "^18.12.0",
"@playwright/test": "1.17.1",
"@rollup/plugin-babel": "^5.3.0",
"@rollup/plugin-node-resolve": "^13.1.3",
"@rollup/plugin-replace": "^3.0.1",
Expand Down Expand Up @@ -181,6 +181,7 @@
]
},
"dependencies": {
"exceljs": "^4.3.0",
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does it make sense for direct dependencies to be locked with ~?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't have an opinion on this subject. I had a look at core repo, all the dependencies are with ^

"html-webpack-plugin": "^5.5.0"
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,12 @@ import {
GridCsvExportOptions,
GridExportFormat as ExportTypes,
GridPrintExportOptions,
GridExcelExportOptions,
} from '../../models/gridExport';
import { useGridRootProps } from '../../hooks/utils/useGridRootProps';
import { gridClasses } from '../../gridClasses';
import { GridSignature } from '../../hooks/utils/useGridApiEventHandler';
import { DataGridProProps } from '../../models/props/DataGridProProps';

interface GridExportDisplayOptions {
/**
Expand All @@ -32,11 +35,12 @@ interface GridExportMenuItemsParams {
export interface GridToolbarExportProps extends ButtonProps {
csvOptions?: GridCsvExportOptions & GridExportDisplayOptions;
printOptions?: GridPrintExportOptions & GridExportDisplayOptions;
excelOptions?: GridExcelExportOptions & GridExportDisplayOptions;
}

const GridToolbarExport = React.forwardRef<HTMLButtonElement, GridToolbarExportProps>(
function GridToolbarExport(props, ref) {
const { csvOptions, printOptions, onClick, ...other } = props;
const { csvOptions, printOptions, excelOptions = {}, onClick, ...other } = props;
const apiRef = useGridApiContext();
const rootProps = useGridRootProps();
const buttonId = useId();
Expand All @@ -57,6 +61,11 @@ const GridToolbarExport = React.forwardRef<HTMLButtonElement, GridToolbarExportP
format: 'print',
formatOptions: printOptions,
},
{
label: apiRef.current.getLocaleText('toolbarExportExcel'),
format: 'excel',
formatOptions: excelOptions,
},
];

const handleMenuOpen = (event) => {
Expand All @@ -72,6 +81,9 @@ const GridToolbarExport = React.forwardRef<HTMLButtonElement, GridToolbarExportP
case 'print':
apiRef.current.exportDataAsPrint(option.formatOptions);
break;
case 'excel':
apiRef.current.exportDataAsExcel(option.formatOptions);
break;
default:
break;
}
Expand All @@ -88,7 +100,17 @@ const GridToolbarExport = React.forwardRef<HTMLButtonElement, GridToolbarExportP
}
};

if (csvOptions?.disableToolbarButton && printOptions?.disableToolbarButton) {
const allowsExcelExport =
rootProps.signature === GridSignature.DataGridPro &&
(rootProps as DataGridProProps)?.experimentalFeatures?.excelExport;
alexfauquette marked this conversation as resolved.
Show resolved Hide resolved
if (!allowsExcelExport) {
excelOptions.disableToolbarButton = true;
}
if (
csvOptions?.disableToolbarButton &&
printOptions?.disableToolbarButton &&
excelOptions?.disableToolbarButton
) {
return null;
}

Expand Down Expand Up @@ -143,6 +165,14 @@ GridToolbarExport.propTypes = {
// | To update them edit the TypeScript types and run "yarn proptypes" |
// ----------------------------------------------------------------------
csvOptions: PropTypes.object,
excelOptions: PropTypes.shape({
allColumns: PropTypes.bool,
disableToolbarButton: PropTypes.bool,
fields: PropTypes.arrayOf(PropTypes.string),
fileName: PropTypes.string,
getRowsToExport: PropTypes.func,
includeHeaders: PropTypes.bool,
}),
printOptions: PropTypes.object,
} as any;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ export const GRID_DEFAULT_LOCALE_TEXT: GridLocaleText = {
toolbarExportLabel: 'Export',
toolbarExportCSV: 'Download as CSV',
toolbarExportPrint: 'Print',
toolbarExportExcel: 'Download as Excel',

// Columns panel text
columnsPanelTextFieldLabel: 'Find column',
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
import type * as Excel from 'exceljs';
import {
GridCellParams,
GRID_CHECKBOX_SELECTION_COL_DEF,
GridStateColDef,
GridRowId,
GridColDef,
GridValueOptionsParams,
GridValueFormatterParams,
GridApi,
} from '../../../../models';

const getExcelJs = () => import('exceljs');

const getFormattedValueOptions = (
colDef: GridColDef,
{ id, row, field }: GridValueOptionsParams,
api: GridApi,
) => {
// TODO: clean depending on the solution chosen for https://github.com/mui-org/material-ui-x/issues/3806
if (!colDef.valueOptions) {
return [];
}
let valueOptionsFormatted;
if (typeof colDef.valueOptions === 'function') {
valueOptionsFormatted = colDef.valueOptions({ id, row, field });
} else {
valueOptionsFormatted = colDef.valueOptions;
}

if (colDef.valueFormatter) {
valueOptionsFormatted = valueOptionsFormatted.map((option) => {
if (typeof option === 'object') {
return option;
}

const params: GridValueFormatterParams = { field, api, value: option };
return String(colDef.valueFormatter(params));
});
}
return valueOptionsFormatted.map((option) =>
typeof option === 'object' ? option.label : option,
);
};

const serialiseRow = (
id: GridRowId,
columns: GridStateColDef[],
getCellParams: (id: GridRowId, field: string) => GridCellParams,
api: GridApi,
) => {
const row = {};
const dataValidation = {};

const firstCellParams = getCellParams(id, columns[0].field);
const outlineLevel = firstCellParams.rowNode.depth;

columns.forEach((column) => {
const cellParams = getCellParams(id, column.field);
switch (cellParams.colDef.type) {
case 'singleSelect': {
const valueOptions: GridValueOptionsParams = {
id: cellParams.id,
row: cellParams.row,
field: cellParams.field,
};
const formattedValueOptions = getFormattedValueOptions(
cellParams.colDef,
valueOptions,
api,
);
dataValidation[column.field] = {
type: 'list',
allowBlank: true,
formulae: [formattedValueOptions.map((x) => `"${x}"`)],
alexfauquette marked this conversation as resolved.
Show resolved Hide resolved
};
const formattedValue = getCellParams(id, column.field).formattedValue;
row[column.field] =
typeof formattedValue === 'object' ? formattedValue.label : formattedValue;
break;
}
case 'boolean':
case 'number':
case 'date':
case 'dateTime':
row[column.field] = getCellParams(id, column.field).value;
alexfauquette marked this conversation as resolved.
Show resolved Hide resolved
break;
case 'actions':
break;
default:
row[column.field] = getCellParams(id, column.field).formattedValue;
break;
}
});
return {
row,
dataValidation,
outlineLevel,
};
};

const serialiseColumn = (column: GridColDef, includeHeaders: boolean) => {
const { field, headerName } = column;

return {
...(includeHeaders ? { header: headerName || field } : {}),
key: field,
// TODO (clean that hack)
// the width seems to be the number of small character visible in a cell
// could be nice to move from px width to excel width
width: column.width ? Math.floor(column.width / 5) : 20,
};
};

interface BuildExcelOptions {
columns: GridStateColDef[];
rowIds: GridRowId[];
getCellParams: (id: GridRowId, field: string) => GridCellParams;
includeHeaders: boolean;
}

export async function buildExcel(options: BuildExcelOptions, api): Promise<Excel.Workbook> {
const { columns, rowIds, getCellParams, includeHeaders } = options;

const columnsWithoutCheckbox = columns.filter(
(column) => column.field !== GRID_CHECKBOX_SELECTION_COL_DEF.field,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe we can remove the checkbox column when the columns are being organized, in the useExcelExport hook?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes it makes sense. I also moved this filter from csvSerializer to useCSVExport to have a utils used by both the CSV and the Excel

);

const excelJS = await getExcelJs();
const workbook: Excel.Workbook = new excelJS.Workbook();
const worksheet = workbook.addWorksheet('Sheet1');
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we allow the name of the sheet to be passed as an input?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I thought about it, but as long as we use only one sheet per workbook, I don't see the interest


worksheet.columns = columnsWithoutCheckbox.map((column) =>
serialiseColumn(column, includeHeaders),
);

rowIds.forEach((id) => {
const { row, dataValidation, outlineLevel } = serialiseRow(
id,
columnsWithoutCheckbox,
getCellParams,
api,
);
const newRow = worksheet.addRow(row);

Object.keys(dataValidation).forEach((field) => {
newRow.getCell(field).dataValidation = {
...dataValidation[field],
};
});

if (outlineLevel) {
newRow.outlineLevel = outlineLevel;
}
});
return workbook;
}
Loading