본문으로 바로가기 본문 바로가기
WIKI 기술 지식 베이스

Data Grid - 수식(Formulas) [<span class="plan-premium"></span>](/x/introduction/licensing/#premium-plan 'Premium plan')

원문 보기 위키 갱신

Data Grid - 수식(Formulas)

스프레드시트 같은 수식으로 사용자가 다른 셀에서 셀 값을 파생할 수 있게 해줘요.

출처: MUI X documentation

본문

allowFormulas로 옵트인한 열에서는 =로 시작하는 문자열 셀 값이 파싱되고 평가돼요. 평가된 값은 렌더링, 정렬, 필터링, 집계, 클립보드 복사, 내보내기에 흐르고, 수식 소스는 행 데이터에 저장된 값으로 남아요.

아래 데모는 모든 Amount 셀이 수식인 인보이스예요. 수량, 단가, 할인을 편집하면 줄 금액, 소계, 세금, 총액이 순서대로 업데이트되는 걸 볼 수 있어요.

import * as React from 'react';
import { DataGridPremium, GridColDef, GridRowsProp } from '@mui/x-data-grid-premium';
import { formulaFeature } from '@mui/x-data-grid-premium/formula';

const currencyFormatter = new Intl.NumberFormat('en-US', {
  style: 'currency',
  currency: 'USD',
});

const columns: GridColDef[] = [
  { field: 'item', headerName: 'Line item', width: 190 },
  {
    field: 'quantity',
    headerName: 'Qty',
    type: 'number',
    width: 70,
    editable: true,
  },
  {
    field: 'unitPrice',
    headerName: 'Unit price',
    type: 'number',
    width: 110,
    editable: true,
    valueFormatter: (value) =>
      typeof value === 'number' ? currencyFormatter.format(value) : value,
  },
  {
    field: 'discount',
    headerName: 'Discount %',
    type: 'number',
    width: 100,
    editable: true,
  },
  {
    field: 'total',
    headerName: 'Amount',
    type: 'number',
    width: 150,
    allowFormulas: true,
    editable: true,
    valueFormatter: (value) =>
      typeof value === 'number' ? currencyFormatter.format(value) : value,
  },
];

const rows: GridRowsProp = [
  {
    id: 1,
    item: 'Laptop workstation',
    quantity: 4,
    unitPrice: 1650,
    total: '=ROUND(quantity * unitPrice * (1 - discount / 100), 2)',
  },
  {
    id: 2,
    item: 'Ultrawide monitor',
    quantity: 8,
    unitPrice: 420,
    discount: 10,
    total: '=ROUND(quantity * unitPrice * (1 - discount / 100), 2)',
  },
  {
    id: 3,
    item: 'Docking station',
    quantity: 8,
    unitPrice: 185,
    total: '=ROUND(quantity * unitPrice * (1 - discount / 100), 2)',
  },
  {
    id: 4,
    item: 'Mechanical keyboard',
    quantity: 8,
    unitPrice: 95,
    discount: 5,
    total: '=ROUND(quantity * unitPrice * (1 - discount / 100), 2)',
  },
  {
    id: 5,
    item: 'Wireless mouse',
    quantity: 8,
    unitPrice: 45,
    discount: 5,
    total: '=ROUND(quantity * unitPrice * (1 - discount / 100), 2)',
  },
  {
    id: 6,
    item: 'Thunderbolt cable',
    quantity: 12,
    unitPrice: 29,
    total: '=ROUND(quantity * unitPrice * (1 - discount / 100), 2)',
  },
  {
    id: 7,
    item: 'On-site setup (hours)',
    quantity: 6,
    unitPrice: 120,
    total: '=ROUND(quantity * unitPrice * (1 - discount / 100), 2)',
  },
  {
    id: 8,
    item: 'Extended warranty',
    quantity: 4,
    unitPrice: 210,
    discount: 15,
    total: '=ROUND(quantity * unitPrice * (1 - discount / 100), 2)',
  },
];

const bottomPinnedRows: GridRowsProp = [
  {
    id: 9,
    item: 'Subtotal',
    total: '=SUM(COLUMN_VALUES("total"))',
  },
  {
    id: 10,
    item: 'Sales tax (8.25%)',
    total: '=ROUND(REF(COLUMN("total"), ROW(9)) * 0.0825, 2)',
  },
  {
    id: 11,
    item: 'Total due',
    total: '=REF(COLUMN("total"), ROW(9)) + REF(COLUMN("total"), ROW(10))',
  },
];

export default function FormulaBasic() {
  return (
    <div style={{ height: 400, width: '100%' }}>
      <DataGridPremium
        featureDependencies={{ formula: formulaFeature }}
        rows={rows}
        columns={columns}
        formulaA1Notation
        rowSelection={false}
        density="compact"
        showCellVerticalBorder
        showColumnVerticalBorder
        disablePivoting
        pinnedRows={{
          bottom: bottomPinnedRows,
        }}
      />
    </div>
  );
}

연산자, 셀 참조, 범위, 내장 함수, 오류 값까지 포함한 완전한 수식 언어는 구문 참조(Syntax reference) 페이지를 참고하세요. 평가가 어떻게 동작하고 커스텀 함수를 등록하는 방법은 Formula engine 페이지에서 설명해요.

수식 활성화

수식 런타임—파서, 평가 엔진, 수식 편집기—은 그리드에 번들로 포함되지 않으므로, 수식을 사용하지 않는 애플리케이션은 번들 크기에서 그 비용을 지불하지 않아요. 수식을 활성화하려면 @mui/x-data-grid-premium/formula 진입점에서 해당 기능을 가져와 featureDependencies prop으로 주입하세요:

import { DataGridPremium } from '@mui/x-data-grid-premium';
import { formulaFeature } from '@mui/x-data-grid-premium/formula';

<DataGridPremium featureDependencies={{ formula: formulaFeature }} />;

이 prop은 그리드가 마운트될 때 읽히며 이후에는 바뀌면 안 돼요. 이 prop이 없으면 = 셀 값은 일반 문자열로 렌더링되고 수식 props는 아무 효과가 없어요. 개발 빌드에서는 누락된 의존성을 가리키는 콘솔 경고가 표시돼요.

:::info 런타임 값인 수식 관련 모든 것—formulaFeature, FormulaBar 컴포넌트, GRID_FORMULA_FUNCTIONS 내장 함수 세트—은 @mui/x-data-grid-premium/formula에서 내보냅니다. 수식 TypeScript 타입은 패키지 루트에서 계속 사용할 수 있어요. :::

기능을 주입하면 수식 지원은 열별로 옵트인됩니다:

const columns: GridColDef[] = [
  { field: 'price', type: 'number' },
  { field: 'quantity', type: 'number' },
  { field: 'total', type: 'number', allowFormulas: true, editable: true },
];

const rows = [{ id: 1, price: 2, quantity: 3, total: '=price * quantity' }];

allowFormulas가 없으면 =로 시작하는 값은 일반 문자열로 렌더링돼요. 수식 열에 =로 시작하는 리터럴 문자열을 저장하려면 앞에 아포스트로피를 붙이세요: '=not a formula.

disableFormulas prop을 사용해 런타임에 전체 그리드의 평가를 끌 수 있어요. featureDependencies를 생략하는 것과 달리, 그리드가 마운트된 동안 토글할 수 있어요.

편집

수식 셀이 편집 모드에 들어가면 편집기는 평가된 값 대신 수식 소스를 보여줘요. number 열에서도 마찬가지예요. 일반 셀을 수식 셀로 만들려면 =를 입력하세요. 수식 편집기는 열 타입과 관계없이 열려요. 일반 셀을 더블클릭하면 열 타입의 기본 편집기가 열리고, 커스텀 renderEditCell이 있는 열은 항상 자신의 편집기를 유지해요.

  • 변경 없이 편집을 커밋하면 수식이 그대로 유지돼요. 행 편집 모드에서도 마찬가지예요.
  • 수식을 제거하려면 그 자리에 일반 값을 커밋하거나 셀 내용을 지우세요.
  • 수식은 한 줄 텍스트예요. 입력하거나 붙여넣은 내용의 줄바꿈은 제거되며, Enter가 편집을 커밋해요. 긴 수식은 편집기에서 시각적으로 줄바꿈되지만 실제 줄바꿈을 포함하지는 않아요.

수식 편집기는 셀 위에 떠서 수식과 함께 커져서, 입력하는 동안 전체 수식이 보여요. 먼저 이웃 셀 위로, 그리드의 보이는 가장자리까지 확장돼요. 가로 공간이 부족하면 수식이 줄바꿈되고 편집기는 대신 전체 줄 단위로 자라요. 아래 행 위로, 셀이 그리드 맨 아래에 있으면 위 행 위로—최대 다섯 줄까지, 이후에는 편집기 안에서 텍스트가 스크롤돼요. 콘텐츠를 삭제해도 편집 도중에는 편집기가 줄어들지 않아요. 행 편집 모드에서는 포커스된 셀만 떠 있는 편집기를 보여주고, 행의 다른 수식 셀은 현재 초안을 그 자리에 표시해요.

수식 텍스트는 고정폭(monospace) 글꼴로 설정돼요. 그래서 그것이 코드임을 읽을 수 있고, 수식 바가 둘 다 렌더링할 때 수식이 일반 값과 한눈에 구별돼요. 연산자, 괄호, 쉼표, 앞의 =는 보조 텍스트 색을 사용하고, 함수 이름·식별자·리터럴이 줄을 이끌게 해요. 테마에서 --DataGrid-formulaFontFamily CSS 변수를 덮어써 글꼴을 바꿀 수 있어요.

processRowUpdate와 실행 취소/다시 실행은 수식 소스에 대해 동작하므로, 행을 지속시키고 복원해도 수식이 자동으로 잘 동작해요:

<DataGridPremium
  processRowUpdate={async (newRow) => {
    // newRow.total === '=price * quantity'
    await saveRow(newRow);
    return newRow;
  }}
/>

자동 완성

수식을 편집하는 동안 제안 드롭다운이 캐럿 위치의 일부 토큰에 대한 순위가 매겨진 완성을 제공해요: 함수, 참조, 상수, 그리드의 열 필드(formulaA1Notation이 활성화되면 열 문자도 추가). 함수를 수락하면 여는 괄호와 함께 삽입되고 캐럿이 안에 놓이며, 캐럿이 호출 안에 있는 동안 시그니처 도움말이 나타나요. 제안은 캐럿 위치에 이어붙여져서 수식의 나머지 부분이 보존돼요.

아래 데모는 커스텀 MARGIN 함수를 등록해요. 빈 Gross margin 셀을 클릭하고 =M을 입력하면 시그니처 도움말과 함께 드롭다운에서 볼 수 있어요.

import * as React from 'react';
import {
  DataGridPremium,
  GridColDef,
  GridRowsProp,
  GridFormulaFunctionDefinition,
} from '@mui/x-data-grid-premium';
import {
  formulaFeature,
  GRID_FORMULA_FUNCTIONS,
} from '@mui/x-data-grid-premium/formula';

const currencyFormatter = new Intl.NumberFormat('en-US', {
  style: 'currency',
  currency: 'USD',
});

const percentFormatter = new Intl.NumberFormat('en-US', {
  style: 'percent',
  maximumFractionDigits: 1,
});

// A custom function appears in the suggestion dropdown with the optional
// `signature`, `description` and `category` metadata it declares.
const MARGIN: GridFormulaFunctionDefinition = {
  name: 'MARGIN',
  minArgs: 2,
  maxArgs: 2,
  signature: 'MARGIN(revenue, cost)',
  description: 'Gross margin as a fraction of revenue.',
  category: 'Finance',
  apply: ([revenue, cost], context) => {
    const income = context.coerce.toNumber(revenue);
    const expense = context.coerce.toNumber(cost);
    if (typeof income !== 'number') {
      return income;
    }
    if (typeof expense !== 'number') {
      return expense;
    }
    return (income - expense) / income;
  },
};

const formulaFunctions = { ...GRID_FORMULA_FUNCTIONS, MARGIN };

const columns: GridColDef[] = [
  { field: 'product', headerName: 'Product', width: 190 },
  {
    field: 'revenue',
    headerName: 'Revenue',
    type: 'number',
    width: 120,
    editable: true,
    valueFormatter: (value) =>
      typeof value === 'number' ? currencyFormatter.format(value) : value,
  },
  {
    field: 'cost',
    headerName: 'Cost',
    type: 'number',
    width: 120,
    editable: true,
    valueFormatter: (value) =>
      typeof value === 'number' ? currencyFormatter.format(value) : value,
  },
  {
    field: 'margin',
    headerName: 'Gross margin',
    type: 'number',
    width: 170,
    allowFormulas: true,
    editable: true,
    valueFormatter: (value) =>
      typeof value === 'number' ? percentFormatter.format(value) : value,
  },
];

const rows: GridRowsProp = [
  {
    id: 1,
    product: 'Cloud subscription',
    revenue: 148000,
    cost: 31000,
    margin: '=MARGIN(revenue, cost)',
  },
  {
    id: 2,
    product: 'Enterprise support',
    revenue: 96500,
    cost: 54200,
    margin: '=MARGIN(revenue, cost)',
  },
  {
    id: 3,
    product: 'Implementation services',
    revenue: 72400,
    cost: 61800,
    margin: '=MARGIN(revenue, cost)',
  },
  {
    id: 4,
    product: 'Training workshops',
    revenue: 28900,
    cost: 16400,
    margin: '=MARGIN(revenue, cost)',
  },
  {
    id: 5,
    product: 'Hardware resale',
    revenue: 54100,
    cost: 47600,
    margin: '=MARGIN(revenue, cost)',
  },
  // The last margin is left empty on purpose: click it and type `=M` to see
  // the custom MARGIN function in the dropdown, with its signature help.
  {
    id: 6,
    product: 'Marketplace add-ons',
    revenue: 19700,
    cost: 8300,
  },
];

export default function FormulaAutocomplete() {
  return (
    <div style={{ height: 340, width: '100%' }}>
      <DataGridPremium
        featureDependencies={{ formula: formulaFeature }}
        rows={rows}
        columns={columns}
        formulaFunctions={formulaFunctions}
        rowSelection={false}
        density="compact"
        showCellVerticalBorder
        showColumnVerticalBorder
        disablePivoting
      />
    </div>
  );
}

드롭다운은 기본적으로 켜져 있어요. 열려 있는 동안 Down과 Up은 하이라이트를 이동하고, Enter와 Tab은 하이라이트된 제안을 수락하며, Escape는 닫아요. 그래서 드롭다운이 닫힐 때까지 그 키들은 편집을 커밋하거나 셀 사이를 이동하지 않아요. 드롭다운을 끄려면 disableFormulaAutocomplete prop을 전달하세요.

참조 하이라이팅

수식을 편집하는 동안 각각의 서로 다른 셀, 범위, 열 참조가 편집기에서 각자의 색으로 표시되고, 가리키는 셀은 그리드에서 이에 맞는 점선 사각형으로 윤곽이 그려져요. 그래서 수식이 무엇을 읽는지 쉽게 알 수 있어요.

아래 데모에서 아무 Q1 total 셀을 더블클릭하면 세 개의 참조가 하이라이트되고, All departments 셀을 더블클릭하면 범위 윤곽을 볼 수 있어요.

import * as React from 'react';
import { DataGridPremium, GridColDef, GridRowsProp } from '@mui/x-data-grid-premium';
import { formulaFeature } from '@mui/x-data-grid-premium/formula';

const currencyFormatter = new Intl.NumberFormat('en-US', {
  style: 'currency',
  currency: 'USD',
  maximumFractionDigits: 0,
});

const monthColumn = (field: string, headerName: string): GridColDef => ({
  field,
  headerName,
  type: 'number',
  width: 110,
  allowFormulas: true,
  editable: true,
  valueFormatter: (value) =>
    typeof value === 'number' ? currencyFormatter.format(value) : value,
});

const columns: GridColDef[] = [
  { field: 'department', headerName: 'Department', width: 170 },
  monthColumn('jan', 'January'),
  monthColumn('feb', 'February'),
  monthColumn('mar', 'March'),
  {
    field: 'q1',
    headerName: 'Q1 total',
    type: 'number',
    width: 140,
    allowFormulas: true,
    editable: true,
    valueFormatter: (value) =>
      typeof value === 'number' ? currencyFormatter.format(value) : value,
  },
];

const rows: GridRowsProp = [
  {
    id: 1,
    department: 'Engineering',
    jan: 118000,
    feb: 122500,
    mar: 131000,
    // Three distinct references — each gets its own color while editing.
    q1: '=jan + feb + mar',
  },
  {
    id: 2,
    department: 'Marketing',
    jan: 64200,
    feb: 58900,
    mar: 71400,
    q1: '=jan + feb + mar',
  },
  {
    id: 3,
    department: 'Sales',
    jan: 83500,
    feb: 90100,
    mar: 96800,
    q1: '=jan + feb + mar',
  },
  {
    id: 4,
    department: 'Operations',
    jan: 42700,
    feb: 44300,
    mar: 43900,
    q1: '=jan + feb + mar',
  },
];

// Summary rows are pinned: a range window covers view positions of the data
// band, so a pinned total can never be swept into its own range by sorting.
const pinnedRows = {
  bottom: [
    // Row data stores the canonical syntax; the editor displays these windows
    // as `=SUM(B1:B4)`, `=SUM(E1:E4)`, and so on.
    {
      id: 5,
      department: 'All departments',
      jan: '=SUM(RANGE_REF(COLUMN_FROM(2), ROW_FROM(1), COLUMN_TO(2), ROW_TO(4)))',
      feb: '=SUM(RANGE_REF(COLUMN_FROM(3), ROW_FROM(1), COLUMN_TO(3), ROW_TO(4)))',
      mar: '=SUM(RANGE_REF(COLUMN_FROM(4), ROW_FROM(1), COLUMN_TO(4), ROW_TO(4)))',
      q1: '=SUM(RANGE_REF(COLUMN_FROM(5), ROW_FROM(1), COLUMN_TO(5), ROW_TO(4)))',
    },
    // Three single-cell references into the pinned summary row: displays as
    // `=ROUND((B5 + C5 + D5) / 3 * 4, 0)`, each reference with its own color.
    {
      id: 6,
      department: 'Annual run rate',
      q1: '=ROUND((REF(COLUMN("jan"), ROW(5)) + REF(COLUMN("feb"), ROW(5)) + REF(COLUMN("mar"), ROW(5))) / 3 * 4, 0)',
    },
  ],
};

export default function FormulaReferenceHighlighting() {
  return (
    <div style={{ height: 340, width: '100%' }}>
      <DataGridPremium
        featureDependencies={{ formula: formulaFeature }}
        rows={rows}
        pinnedRows={pinnedRows}
        columns={columns}
        formulaA1Notation
        rowSelection={false}
        density="compact"
        showCellVerticalBorder
        showColumnVerticalBorder
        disablePivoting
      />
    </div>
  );
}
  • 색상은 해석된 대상(resolved target) 기준으로 키가 지정되므로, 같은 셀을 가리키는 두 참조는 색을 공유하고 수식에서 반복되는 참조는 한 번만 윤곽이 그려져요.
  • 해석할 수 없는 참조—숨겨진 열, 필터링된 행, 또는 편집 중인 셀 자체—는 색이 지정되지 않고 윤곽도 그려지지 않아요.
  • 고정 열이나 고정 행의 셀을 가리키는 참조는 편집기에서 색을 유지하지만 그리드에는 사각형이 그려지지 않아요. 고정 섹션이 하이라이트 오버레이 위에 그려지기 때문이에요.
  • 하이라이팅은 표준(canonical) 구문과 A1 구문 모두에서 동작해요.
  • 커스텀 renderEditCell이 있는 열은 편집기를 완전히 제어하므로 하이라이트되지 않아요.

팔레트는 열 가지 색을 포함하며, 수식 편집기와 하이라이트 오버레이의 --DataGrid-formulaRefColor-0부터 --DataGrid-formulaRefColor-9까지의 CSS 변수로 노출되고 테마에서 덮어쓸 수 있어요.

수식 바

slotProps.toolbar.formulaBar로 기본 툴바에 스프레드시트 스타일 수식 바를 활성화하세요:

<DataGridPremium
  showToolbar
  featureDependencies={{ formula: formulaFeature }}
  slotProps={{ toolbar: { formulaBar: true } }}
/>

이 바는 포커스된 셀을 위한 영구적으로 열려 있는 수식 편집기예요:

  • 셀이 **보기 모드(view mode)**인 동안 바에 입력하면 초안을 편집해요. 참조는 그리드에서 색이 지정되고 윤곽이 그려지며, 초안의 결과는 입력 옆에서 즉석으로 평가돼요. 입력하는 동안에는 아무것도 커밋되지 않아요. Enter는 초안을 커밋하고(processRowUpdate를 통해, 단일 실행 취소 단계로) 포커스를 아래로 이동하고, Tab은 커밋하고 오른쪽으로 이동하며, 다른 셀을 클릭하거나 바를 떠나는 것도 커밋해요. Escape만이 버리는 유일한 방법이에요.
  • 셀이 **편집 모드(edit mode)**인 동안 바는 편집기의 실시간 미러예요. 셀에 입력하면 바에 나타나고, 바에 입력하면 셀에 나타나며, 바와 상호작용해도 셀의 편집기를 닫지 않아요.

아래 데모에서 아무 Amount 셀을 클릭하고 바에서 그 수식을 편집하거나, 셀을 더블클릭해서 바가 편집을 미러링하는 걸 보세요.

import * as React from 'react';
import { DataGridPremium, GridColDef, GridRowsProp } from '@mui/x-data-grid-premium';
import { formulaFeature } from '@mui/x-data-grid-premium/formula';

const currencyFormatter = new Intl.NumberFormat('en-US', {
  style: 'currency',
  currency: 'USD',
});

const columns: GridColDef[] = [
  { field: 'item', headerName: 'Line item', width: 190 },
  {
    field: 'quantity',
    headerName: 'Qty',
    type: 'number',
    width: 70,
    editable: true,
  },
  {
    field: 'unitPrice',
    headerName: 'Unit price',
    type: 'number',
    width: 110,
    editable: true,
    valueFormatter: (value) =>
      typeof value === 'number' ? currencyFormatter.format(value) : value,
  },
  {
    field: 'total',
    headerName: 'Amount',
    type: 'number',
    width: 150,
    allowFormulas: true,
    editable: true,
    valueFormatter: (value) =>
      typeof value === 'number' ? currencyFormatter.format(value) : value,
  },
];

const rows: GridRowsProp = [
  {
    id: 1,
    item: 'Laptop workstation',
    quantity: 4,
    unitPrice: 1650,
    total: '=quantity * unitPrice',
  },
  {
    id: 2,
    item: 'Ultrawide monitor',
    quantity: 8,
    unitPrice: 420,
    total: '=quantity * unitPrice',
  },
  {
    id: 3,
    item: 'Docking station',
    quantity: 8,
    unitPrice: 185,
    total: '=quantity * unitPrice',
  },
  {
    id: 4,
    item: 'Thunderbolt cable',
    quantity: 12,
    unitPrice: 29,
    total: '=quantity * unitPrice',
  },
];

const pinnedRows = {
  bottom: [
    {
      id: 5,
      item: 'Total due',
      // The window covers view positions D1:D4 — pinned rows sit outside the
      // sortable data band, so the total can never be swept into its own range.
      total: '=SUM(RANGE_REF(COLUMN_FROM(4), ROW_FROM(1), COLUMN_TO(4), ROW_TO(4)))',
    },
  ],
};

export default function FormulaBarBasic() {
  return (
    <div style={{ height: 480, width: '100%' }}>
      <DataGridPremium
        featureDependencies={{ formula: formulaFeature }}
        rows={rows}
        pinnedRows={pinnedRows}
        columns={columns}
        formulaA1Notation
        showToolbar
        slotProps={{ toolbar: { formulaBar: true } }}
        rowSelection={false}
        density="compact"
        showCellVerticalBorder
        showColumnVerticalBorder
        disablePivoting
      />
    </div>
  );
}

바를 커스텀 툴바에 배치하거나 포털을 통해 페이지 어디든 두려면 내보낸 컴포넌트를 조합하세요. Formula Bar 컴포넌트 페이지를 참고하세요.

복사, 붙여넣기, 채우기

클립보드 복사는 평가된 값을 클립보드에 넣고 수식은 넣지 않아요. 반대로 allowFormulas 열에 =로 시작하는 문자열을 붙여넣으면 수식으로 저장돼요. formulaA1Notation이 활성화되면 붙여넣은 수식의 상대 A1 참조는 각 셀이 붙여넣기 원점에서 떨어진 거리만큼 오프셋됩니다. 스프레드시트가 조정하는 방식과 같아요.

그리드 안에서 셀들로 수식을 복제하려면 채우기 핸들을 사용하세요.

채우기 핸들

셀 선택 채우기 핸들이 활성화되어 있을 때(cellSelection과 cellSelectionFillHandle), 수식 셀을 끌거나(Ctrl+D(아래로 채우기) 또는 Ctrl+R(오른쪽으로 채우기)) 수식을 복사하고 각 대상 셀에 맞게 참조를 조정해요.

아래 데모에서 첫 번째 Total with tax 셀을 선택하고 채우기 핸들을 아래로 끌어보세요. 상대 amount 참조는 각 행을 따라가고, 절대 $C$1 참조는 공유 세율에 고정된 채 유지돼요. 그런 다음 세율을 편집하면 모든 총액이 업데이트되는 걸 볼 수 있어요.

import * as React from 'react';
import { DataGridPremium, GridColDef, GridRowsProp } from '@mui/x-data-grid-premium';
import { formulaFeature } from '@mui/x-data-grid-premium/formula';

const currencyFormatter = new Intl.NumberFormat('en-US', {
  style: 'currency',
  currency: 'USD',
});

const columns: GridColDef[] = [
  { field: 'order', headerName: 'Order', width: 140 },
  {
    field: 'amount',
    headerName: 'Amount',
    type: 'number',
    width: 110,
    editable: true,
    valueFormatter: (value) =>
      typeof value === 'number' ? currencyFormatter.format(value) : value,
  },
  {
    field: 'rate',
    headerName: 'Tax %',
    type: 'number',
    width: 90,
    editable: true,
  },
  {
    field: 'total',
    headerName: 'Total with tax',
    type: 'number',
    width: 160,
    allowFormulas: true,
    editable: true,
    valueFormatter: (value) =>
      typeof value === 'number' ? currencyFormatter.format(value) : value,
  },
];

// Only the first row holds a formula: `=ROUND(amount * (1 + $C$1 / 100), 2)`
// in A1 notation. The `amount` reference is relative and the `$C$1` tax-rate
// reference is absolute. Select the first "Total with tax" cell and drag the
// fill handle down (or press Ctrl+D): `amount` follows each row while `$C$1`
// stays pinned to the shared tax rate.
const rows: GridRowsProp = [
  {
    id: 1,
    order: 'INV-2401',
    amount: 1250,
    rate: 8.25,
    total:
      '=ROUND(amount * (1 + REF(COLUMN_POSITION(3), ROW_POSITION(1)) / 100), 2)',
  },
  { id: 2, order: 'INV-2402', amount: 890 },
  { id: 3, order: 'INV-2403', amount: 2140 },
  { id: 4, order: 'INV-2404', amount: 655 },
  { id: 5, order: 'INV-2405', amount: 1780 },
  { id: 6, order: 'INV-2406', amount: 990 },
];

export default function FormulaFillHandle() {
  return (
    <div style={{ height: 340, width: '100%' }}>
      <DataGridPremium
        featureDependencies={{ formula: formulaFeature }}
        rows={rows}
        columns={columns}
        formulaA1Notation
        cellSelection
        cellSelectionFillHandle
        rowSelection={false}
        density="compact"
        showCellVerticalBorder
        showColumnVerticalBorder
        disablePivoting
      />
    </div>
  );
}
  • 상대 참조는 셀이 이동한 거리만큼 이동합니다: =A1 * B1로 작성된 수식은 한 행 아래에서 =A2 * B2가 되고, =price * quantity 같은 같은 행 필드 참조는 옆으로 채울 때 다음 열로 이동해요.
  • 절대 참조는 고정된 채로 유지됩니다: 위치 참조($A$1 형태)는 절대 이동하지 않아요.
  • 범위 창도 따라갑니다: 일반 범위 끝점은 수식 자체 셀에서의 오프셋으로 저장되므로, 한 행 아래로 채워진 =SUM(B1:B4)는 =SUM(B2:B5)를 읽어요. 복사된 텍스트는 동일하고, 각 복사본은 자기 행에 다시 고정됩니다. $ 축은 고정된 채로 남으므로, 아래로 채워진 =SUM($A$1:A1)은 누계를 만듭니다. Ranges를 참고하세요.
  • 오프셋은 현재 정렬 및 필터링된 보기 순서로 측정되므로, 채우기는 표시된 대로 행을 존중해요.
  • 첫 번째 행이나 열을 지나 이동하는 단일 셀 참조는 원래 대상을 유지하고, 마지막 행이나 열을 지나 이동하는 것은 #REF!로 해석됩니다. 창이 데이터 행 밖에 끝나는 범위도 스프레드시트에서처럼 #REF! 오류예요.

allowFormulas가 아닌 열에 수식을 채우면 수식 대신 소스 셀의 평가된 값을 복사하므로, =… 문자열이 일반 열에 저장되는 일은 없어요.

Excel 내보내기

기본적으로 Excel 내보내기는 각 수식 셀의 평가된 값을 씁니다. 수식 자체를 내보내려면—스프레드시트가 재계산하는 실제 Excel 수식으로—escapeFormulas: false를 설정하세요.

툴바의 excelOptions로 전달해서 내장 Export 버튼이 사용하게 하세요:

<DataGridPremium
  showToolbar
  slotProps={{
    toolbar: {
      excelOptions: { escapeFormulas: false },
    },
  }}
/>

또는 API를 통해 내보낼 때 직접 전달하세요:

apiRef.current.exportDataAsExcel({ escapeFormulas: false });

내보낸 참조는 헤더 행과 내보낸 열·행 순서를 고려해 내보낸 시트에서 각 셀의 위치를 가리키는 Excel A1 표기법으로 다시 쓰여요. formulaA1Notation prop과는 무관해요. 상대 참조는 상대(B2)로, 절대 참조는 절대($B$2)로 유지되어 그리드와 일치해요. 범위 창의 경우 축은 정확히 FIXED()일 때 $로 내보내져요. Excel 자체는 범위 끝점을 수식 셀에서의 오프셋으로 저장하는데, 이는 그리드가 저장하는 방식과 정확히 같아요. 그래서 Excel 안에서 복사, 채우기, 정렬이 그리드에서처럼 동작해요.

  • 내보내기 밖의 셀을 가리키는 참조—필터링된 행, 또는 disableExport나 fields 옵션으로 제거된 열—은 #REF! 오류로 표시됩니다.
  • 셀은 호출하는 모든 함수가 그리드에 등록되어 있을 때만 커스텀 함수를 포함해 실제 수식으로 내보내져요. 알 수 없는 함수를 호출하는 수식은 대신 평가된 값을 내보내므로, 신뢰할 수 없는 행 데이터가 스프레드시트 평가 수식을 파일에 몰래 넣을 수 없어요.
  • 등록된 함수는 변경 없이 내보내져요. Excel이 인식하지 못하는 커스텀 함수는 캐시된 값을 유지하지만 스프레드시트가 재계산하면 #NAME?를 보여줘요.
  • COLUMN_VALUES와 RANGE_REF는 연속된 A1 범위로 내보내져요. 내보내기에 그룹화되거나 고정된 행이 포함되면 그 범위도 그것을 덮으므로, 값은 정확하지만 Excel에서 수동으로 재계산하면 다를 수 있어요.
  • CSV 내보내기는 항상 평가된 값을 씁니다.

아래 데모는 상환(payment) 수식으로 모기지 제안을 비교해요. 툴바로 내보내고 Excel에서 파일을 연 다음 APR을 바꿔보세요. 월 상환액과 최적 제안이 Excel 안에서 재계산됩니다. 셀이 실제 수식을 담고 있기 때문이에요.

import * as React from 'react';
import { DataGridPremium, GridColDef, GridRowsProp } from '@mui/x-data-grid-premium';
import { formulaFeature } from '@mui/x-data-grid-premium/formula';

const currencyFormatter = new Intl.NumberFormat('en-US', {
  style: 'currency',
  currency: 'USD',
});

const columns: GridColDef[] = [
  { field: 'lender', headerName: 'Lender', width: 180 },
  {
    field: 'principal',
    headerName: 'Principal',
    type: 'number',
    width: 120,
    editable: true,
    valueFormatter: (value) =>
      typeof value === 'number' ? currencyFormatter.format(value) : value,
  },
  {
    field: 'apr',
    headerName: 'APR %',
    type: 'number',
    width: 90,
    editable: true,
  },
  {
    field: 'years',
    headerName: 'Years',
    type: 'number',
    width: 80,
    editable: true,
  },
  {
    field: 'payment',
    headerName: 'Monthly payment',
    type: 'number',
    width: 170,
    allowFormulas: true,
    editable: true,
    valueFormatter: (value) =>
      typeof value === 'number' ? currencyFormatter.format(value) : value,
  },
];

// Standard amortized-loan payment: P * r / (1 - (1 + r)^(-n)) with a monthly
// rate. After exporting, change an APR in Excel — the payment and the best
// offer recalculate there, because the cells hold live formulas.
const monthlyPayment =
  '=ROUND(principal * (apr / 1200) / (1 - POWER(1 + apr / 1200, -12 * years)), 2)';

const rows: GridRowsProp = [
  {
    id: 1,
    lender: 'First National Bank',
    principal: 420000,
    apr: 6.1,
    years: 30,
    payment: monthlyPayment,
  },
  {
    id: 2,
    lender: 'Harbor Credit Union',
    principal: 420000,
    apr: 5.8,
    years: 30,
    payment: monthlyPayment,
  },
  {
    id: 3,
    lender: 'Summit Online Lending',
    principal: 420000,
    apr: 6.4,
    years: 15,
    payment: monthlyPayment,
  },
  {
    id: 4,
    lender: 'Pacific Mortgage Co.',
    principal: 420000,
    apr: 5.95,
    years: 20,
    payment: monthlyPayment,
  },
];

const pinnedRows = {
  bottom: [
    {
      id: 5,
      lender: 'Best offer',
      // A window over view positions E1:E4 — pinned outside the data band, so
      // sorting the lenders can never pull the summary into its own range.
      payment:
        '=MIN(RANGE_REF(COLUMN_FROM(5), ROW_FROM(1), COLUMN_TO(5), ROW_TO(4)))',
    },
  ],
};

export default function FormulaExcelExport() {
  return (
    <div style={{ height: 340, width: '100%' }}>
      <DataGridPremium
        featureDependencies={{ formula: formulaFeature }}
        rows={rows}
        pinnedRows={pinnedRows}
        columns={columns}
        formulaA1Notation
        rowSelection={false}
        density="compact"
        showToolbar
        showCellVerticalBorder
        showColumnVerticalBorder
        disablePivoting
        slotProps={{
          toolbar: {
            excelOptions: {
              escapeFormulas: false,
            },
          },
        }}
      />
    </div>
  );
}

:::warning escapeFormulas는 CSV 및 Excel 수식 주입을 방지하기 위해 기본값이 true입니다. =, +, -, @로 시작하는 모든 문자열 값은 텍스트로 기록돼요. false로 설정하면 그리드 수식을 실제 수식으로 내보내지만, 다른 열의 그런 문자열이 Excel에서 수식으로 실행되게도 합니다. 신뢰할 수 있는 데이터에서만 꺼야 해요. :::

현재 제한 사항

  • 수식은 서버 측 데이터 소스 또는 피벗이 활성화된 상태에서는 지원되지 않아요.
  • 수식 구문은 en-US 전용이며, 내장 함수 메타데이터는 로컬라이즈되지 않아요.
  • 범위와 COLUMN_VALUES는 고정 행을 절대 덮지 않아요. 대신 개별 셀을 참조하세요.
  • 범위 창은 행이 추가되거나 제거될 때 커지거나 줄어들지 않아요. 일반(고정된) 창은 수식에 대한 지오메트리를 유지하고 $(고정) 창은 뷰 위치를 유지하므로, 창 중간에 정렬되는 삽입 행은 창이 덮는 행을 바꿔요.
  • 수식 편집기는 편집기 내 실행 취소를 지원하지 않아요. 커밋된 값의 그리드 수준 실행 취소와 다시 실행은 평소처럼 동작해요.
  • 수식 열의 자체 valueGetter는 그 수식 셀에서 무시됩니다(개발 모드 경고가 이를 알려줘요). 열의 일반 셀에는 정상적으로 적용돼요.
  • 클립보드 복사는 평가된 값을 클립보드에 넣어요. 그리드 안에서 수식을 복제하려면 채우기 핸들을 사용하세요.

API

더 알아보기 (Learn more)