跳到內容
+

Data Grid - 彙總

將彙總功能新增至 Data Grid,讓使用者可以組合列值。

您可以透過 Data Grid 介面彙總列,方法是開啟欄選單,然後從彙總下的項目中選取。

彙總值會呈現在 Data Grid 底部的頁尾列中。

將彙總傳遞至 Data Grid

模型的結構

彙總模型是一個物件。鍵對應到欄,值是要使用的彙總函式名稱。

初始化彙總

若要在不控制其狀態的情況下初始化彙總,請將模型提供給 initialState 屬性。

按下 Enter 開始編輯

受控彙總

使用 aggregationModel 屬性來控制傳遞至 Data Grid 的彙總。

使用 onAggregationModelChange 屬性來監聽彙總的變更,並據此更新屬性。

按下 Enter 開始編輯

停用彙總

針對所有欄

若要停用彙總,請將 disableAggregation 屬性設定為 true。即使提供了模型,這也會停用所有與彙總相關的功能。

針對某些欄

若要停用特定欄的彙總,請將其欄定義 (GridColDef) 上的 aggregable 屬性設定為 false

在以下範例中,Year 欄不可彙總,因為其 aggregable 屬性設定為 false

以程式設計方式彙總不可彙總的欄

若要在不可彙總的欄 (欄定義中 aggregable: false 的欄 欄定義) 上以程式設計方式套用彙總,您可以透過下列其中一種方式提供彙總模型

  1. aggregation.model 傳遞至 initialState 屬性。這會使用提供的模型初始化彙總
  2. 提供 aggregationModel 屬性。這會使用提供的模型控制彙總
  3. 呼叫 API 方法 setAggregationModel。這會使用提供的模型設定彙總。

在以下示範中,雖然 Year 欄不可彙總,但透過提供初始彙總模型,它仍以唯讀模式彙總。

搭配列分組使用

啟用列分組後,彙總值會顯示在兩個位置

  1. 在分組列上—Data Grid 會在其分組列上顯示每個群組彙總值。
  2. 在最上層頁尾上—Data Grid 會新增最上層頁尾來彙總所有列,就像處理扁平列清單一樣。

使用 getAggregationPosition 屬性來自訂此行為。此函式會將目前群組節點作為引數 (根群組為 null),並傳回彙總值的位置。此位置必須是下列三個值之一

  1. "footer"—Data Grid 會將頁尾新增至群組以彙總其列。
  2. "inline"—Data Grid 會停用分組列上的彙總。
  3. null—Data Grid 不會彙總群組。
// Will aggregate the root group on the top-level footer and the other groups on their grouping row
// (default behavior)
getAggregationPosition=(groupNode) => (groupNode == null ? 'footer' : 'inline'),

// Will aggregate all the groups on their grouping row
// The root will not be aggregated
getAggregationPosition={(groupNode) => groupNode == null ? null : 'inline'}

// Will only aggregate the company groups on the grouping row
// Director groups and the root will not be aggregated
getAggregationPosition={(groupNode) => groupNode?.groupingField === 'company' ? 'inline' : null}

// Will only aggregate the company group "Universal Pictures" on the grouping row
getAggregationPosition={(groupNode) =>
(groupNode?.groupingField === 'company' &&
  groupNode?.groupingKey === 'Universal Pictures') ? 'inline' : null
}

// Will only aggregate the root group on the top-level footer
getAggregationPosition={(groupNode) => groupNode == null ? 'footer' : null}

以下示範顯示每個群組頁尾上的 SUM 彙總,但最上層頁尾上沒有

按下 Enter 開始編輯

搭配樹狀資料使用

與列分組一樣,您可以將彙總值顯示在頁尾或分組列中。

以下示範顯示 Size 欄上的 SUM 彙總,以及 Last modification 欄上的 MAX 彙總

篩選

依預設,彙總只會使用篩選後的列。若要使用所有列,請將 aggregationRowsScope 設定為 "all"

在以下範例中,電影《阿凡達》未通過篩選,但仍用於 Gross 欄的 MAX 彙總

彙總函式

基本結構

彙總函式是一個物件,描述如何組合給定的一組值。

const minAgg: GridAggregationFunction<number | Date> = {
  // Aggregates the `values` into a single value.
  apply: ({ values }) => Math.min(...values.filter((value) => value != null)),
  // This aggregation function is only compatible with numerical values.
  columnTypes: ['number'],
};

您可以在 GridAggregationFunction API 頁面上找到完整的類型詳細資訊。

內建函式

@mui/x-data-grid-premium 套件隨附一組內建彙總函式,以涵蓋基本使用案例

名稱 行為 支援的欄類型
sum 傳回群組中所有值的總和 數字
avg 傳回群組中所有值的非四捨五入平均值 數字
min 傳回群組的最小值 numberdatedateTime
max 傳回群組的最大值 numberdatedateTime
size 傳回群組中的儲存格數 all

移除內建函式

針對所有欄

若要從所有欄中移除特定的彙總函式,請將篩選後的物件傳遞至 aggregationFunctions 屬性。在以下範例中,SUM 函式已移除

按下 Enter 開始編輯

針對一個欄

若要限制給定欄中的彙總選項,請將 availableAggregationFunctions 屬性傳遞至欄定義。

這可讓您指定哪些選項可用,如下所示

const column = {
  field: 'year',
  type: 'number',
  availableAggregationFunctions: ['max', 'min'],
};

在以下範例中,您可以使用 MAXMIN 函式彙總 Year 欄,而所有函式都可用於 Gross

按下 Enter 開始編輯

建立自訂函式

將自訂彙總函式傳遞至 aggregationFunctions 屬性。

彙總函式是一個具有下列形狀的物件

const firstAlphabeticalAggregation: GridAggregationFunction<string, string | null> =
  {
    // The `apply` method takes the values to aggregate and returns the aggregated value
    apply: (params) => {
      if (params.values.length === 0) {
        return null;
      }

      const sortedValue = params.values.sort((a = '', b = '') => a.localeCompare(b));

      return sortedValue[0];
    },
    // The `label` property defines the label displayed in the column header when this aggregation is being used.
    label: 'firstAlphabetical',
    // The `types` property defines which type of columns can use this aggregation function.
    // Here, we only want to propose this aggregation function for `string` columns.
    // If not defined, aggregation will be available for all column types.
    columnTypes: ['string'],
  };

在以下範例中,Data Grid 針對 string 欄有兩個額外的自訂彙總函式:firstAlphabeticallastAlphabetical

彙總來自多個列欄位的資料

依預設,彙總函式的 apply 方法會接收一個值陣列,代表每個列的單一欄位值。例如,sum 彙總函式會接收 gross 欄位的值。

在以下範例中,profit 欄中的值衍生自列的 grossbudget 欄位

{
  field: 'profit',
  type: 'number',
  valueGetter: (value, row) => {
    if (!row.gross || !row.budget) {
      return null;
    }
    return (row.gross - row.budget) / row.budget;
  }
}

若要彙總 profit 欄,您必須分別計算 grossbudget 欄位的總和,然後使用上述範例中的公式來計算彙總的 profit 值。

若要執行此作業,請在彙總函式上使用 getCellValue 回呼來轉換傳遞至 apply 方法的資料

const profit: GridAggregationFunction<{ gross: number; budget: number }, number> = {
  label: 'profit',
  getCellValue: ({ row }) => ({ budget: row.budget, gross: row.gross }),
  apply: ({ values }) => {
    let budget = 0;
    let gross = 0;
    values.forEach((value) => {
      if (value) {
        gross += value.gross;
        budget += value.budget;
      }
    });
    return (gross - budget) / budget;
  },
  columnTypes: ['number'],
};

自訂值格式器

依預設,彙總儲存格會使用其欄的值格式器。但對於某些欄,彙總值的格式可能需要與其他儲存格值的格式不同。

提供 valueFormatter 方法給彙總函式,以覆寫欄的預設格式設定

const aggregationFunction: GridAggregationFunction = {
  apply: () => {
    /* */
  },
  valueFormatter: (params) => {
    /* format the aggregated value */
  },
};

自訂呈現

如果用於顯示彙總的欄具有 renderCell 屬性,則彙總儲存格會使用 params.aggregation 物件呼叫它,讓您決定要如何呈現它。

此物件包含 hasCellUnit,可讓您知道目前的彙總是否與欄的其餘資料具有相同的單位—例如,如果欄是以 $ 為單位,則彙總值是否也以 $ 為單位?

在以下範例中,您可以看到除了 size 之外,所有彙總函式都以評等 UI 呈現,因為它不是有效的評等

簽章
gridAggregationLookupSelector: (apiRef: GridApiRef) => GridAggregationLookup
// or
gridAggregationLookupSelector: (state: GridState, instanceId?: number) => GridAggregationLookup
範例
gridAggregationLookupSelector(apiRef)
// or
gridAggregationLookupSelector(state, apiRef.current.instanceId)
簽章
gridAggregationModelSelector: (apiRef: GridApiRef) => GridAggregationModel
// or
gridAggregationModelSelector: (state: GridState, instanceId?: number) => GridAggregationModel
範例
gridAggregationModelSelector(apiRef)
// or
gridAggregationModelSelector(state, apiRef.current.instanceId)