How to export all the pages to CSV in MUI DataGrid?

Viewed 1191

I hava a DataGrid table from Material UI with more than 3000 rows, each page contains max 50 rows per page.

What I want is to be able to export all the rows to CSV when I click the export btn.

Actual behavior: Only current page data is being exported

Can anybody give me a hint on what I am doing wrong ?

My code :

 <DataGrid
   rows={users}
   columns={columns}
   pageSize={limit}
   page={page - 1}
   rowCount={rowsCount}
  //rowsPerPageOptions={[limit]}
  pagination
  paginationMode="server"
  components={{
    Toolbar: GridToolbar,
  }}
  onPageChange={(data) => {
   updateUsers(data + 1, formSubmitted);
  }}
/>

DataGrid in the web example : Screensot of DataGrid Table

3 Answers

Your not doing anything wrong, this is the default behavior of the DataGrid.

You will need to use the apiRef of the DataGrid to handle this though. You essentially need to tell the exporter which rows to export. There are a few options for this which is in the documentation I linked at the bottom.

const apiRef = useGridApiRef();

 <DataGrid
   rows={users}
   apiRef={apiRef}
   columns={columns}
   pageSize={limit}
   page={page - 1}
   rowCount={rowsCount}
  //rowsPerPageOptions={[limit]}
  pagination
  paginationMode="server"
  components={{
    Toolbar: GridToolbar,
  }}
  componentsProps={{ toolbar: { csvOptions: { getRowsToExport: () => gridFilteredSortedRowIdsSelector(apiRef) } } }}

  onPageChange={(data) => {
   updateUsers(data + 1, formSubmitted);
  }}
/>

As shown in this sandbox from the mui docs: https://codesandbox.io/s/0zex5c?file=/demo.tsx

Section of the docs which breaks this down: https://mui.com/x/react-data-grid/export/#exported-rows

I am using the same approach of using server-side pagination loading 10 rows at a time. my solution was to use <GridToolbarExport> component and add an onClick prop that requests and updates all my rows just before export.

Furthermore, after the export in order to not waste that large data already requested from server-side I switch the component to client from server until the user refreshes or leaves the page.

<GridToolbarExport
  excelOptions={{ allColumns: true }}
  csvOptions={{ allColumns: true }}
  onClick={() => {
    if (dataMode == 'server') {
      const tableState = apiRef.current.state
      updateRows(tableState, 'all')
      setDataMode('client')
    }
   }
  }
/>

Actually there was no problem with DataGrid, but it was with the api call which was programmed to bring 50 new users each time we change the page to prevent brining too much data at once in the front

To overcome this issue, I created a new button outside datagrid which made an api call when clicked for getting all the data and exporting to CSV using REACT-CSV lib.

Related