Search code examples
javascriptreactjsmaterial-uiexportmui-x-data-grid

Sort the rows data for CSV or Excel export using MUI DataGrid


How to sort the row data for exporting to CSV or Excel using the MUI DataGrid?

Below is my code sample for the toolbar.

      slots={{
        noRowsOverlay: NoDataComponent,
        noResultsOverlay: NoDataComponent,
        toolbar: (
          <GridToolbarExport
            sx={{
              borderRadius: 24
            }}
            variant='contained'
            size='medium'
            disabled={loading || clients.items?.length === 0}
            printOptions={{
              disableToolbarButton: true
            }}
            csvOptions={{
              allColumns: false,
              fields: [
                'createdDateTime',
                'partnerId',
                'company',
                'referenceNumber',
                'fullname',
                'status',
                'currencyType',
                'lastCreditMonitoringDate',
                'approvedLine',
                'availableLine',
                'utilisedLine',
                'nextRenewalDate',
                'creditlineStatus',
                'newShadowLimitDecision',
                'decision',
                // 'dateOfShadowLimitChange',
                'notes',
                'authorizedby'
              ],
              fileName: `Partner_customer_Report_${new Date().getTime()}`
            }}
          />
        ),
        loadingOverlay: () => LoadingSkeleton(pageSize)
      }}

I have tried the diifferent options for the CSV exports as described in the MUI DatGrid site.

I think using the getRowsToExport prop can be helpful to achieve the result, But I don't know how to achieve this?


Solution

  • We can achieve the result using the getRowsToExport prop, just as I have shown below.

      slots={{
        noRowsOverlay: NoDataComponent,
        noResultsOverlay: NoDataComponent,
        toolbar: (
          <GridToolbarExport
            sx={{
              borderRadius: 24
            }}
            variant='contained'
            size='medium'
            disabled={loading || clients.items?.length === 0}
            printOptions={{
              disableToolbarButton: true
            }}
            csvOptions={{
              allColumns: false,
              fields: [
                'createdDateTime',
                'partnerId',
                'company',
                'referenceNumber',
                'fullname',
                'status',
                'currencyType',
                'lastCreditMonitoringDate',
                'approvedLine',
                'availableLine',
                'utilisedLine',
                'nextRenewalDate',
                'creditlineStatus',
                'newShadowLimitDecision',
                'decision',
                'notes',
                'authorizedby'
              ],
              fileName: `Partner_customer_Report_${new Date().getTime()}`,
              getRowsToExport: (params: GridCsvGetRowsToExportParams) => {
                let response = [] as GridRowId[];
    
                if (params.apiRef.current) {
                  params.apiRef.current.setSortModel([{ field: 'referenceNumber', sort: 'asc' }]);
                  response = params.apiRef.current.getSortedRowIds();
                }
    
                return response;
              }
            }}
          />
        ),
        loadingOverlay: () => LoadingSkeleton(pageSize)
      }}
    

    Explanation:

    • First, we can sort the rows based on the required column and order sequence by passing the sorted data to the setSortModel function to arrange the data accordingly.

    • After this sorting operation, we simply return the list of sorted row IDs using the getSortedRowIds function. This prop should return the data in the form of GridRowId[].

    Therefore, the getRowsToExport should be structured as follows.

      getRowsToExport: (params: GridCsvGetRowsToExportParams) => {
                let response = [] as GridRowId[];
    
                if (params.apiRef.current) {
                  params.apiRef.current.setSortModel([{ field: 'referenceNumber', sort: 'asc' }]);
                  response = params.apiRef.current.getSortedRowIds();
                }
    
                return response;
              }
    

    I hope this helps you. Thanks.