본문으로 건너뛰기Skip to content
예제 첫화면Examples home

맨 아래에 합계 줄 붙이기Add a total row at the bottom

컬럼마다 "무엇을 계산할지"만 적어 두면 표 맨 아래에 합계 줄이 생겨요. 합계 말고도 평균, 최소, 최대, 개수를 고를 수 있어요.Say what to calculate for each column and a total row appears at the bottom. Besides the sum you can pick average, minimum, maximum or count.

입문Beginner
직접 써 보기Live preview맨 아래에 합계 줄 붙이기Add a total row at the bottom

코드Code

탭을 골라 코드를 복사하세요. 위 화면은 이 코드를 그대로 실행한 결과예요.Pick a tab and copy the code. The preview above runs exactly this code.

이 화면은 새 모양 옵션을 켠 모양이에요: density: 'spacious', iconStyle: 'soft', motion: true (코드에 없으면 기본 모양으로 보여요)This preview has the new-look options on: density: 'spacious', iconStyle: 'soft', motion: true (without them in your code you get the default look)

빌드 도구(Vite 등)를 쓰는 프로젝트용 모듈 파일이에요. 설치 없이 바로 돌려 보려면 HTML 탭이나 직접 해보기를 쓰세요.

버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.

index.html
<div id="app">
  <div class="toolbar">
    <select aria-label="계산" id="op">
      <option value="sum" selected>합계</option>
      <option value="avg">평균</option>
      <option value="min">최소</option>
      <option value="max">최대</option>
      <option value="count">개수</option>
    </select>
    <select aria-label="합계 줄" id="footer">
      <option value="on" selected>보이기</option>
      <option value="off">숨기기</option>
    </select>
  </div>
  <div id="grid" style="height: 360px"></div>
</div>
<script type="module" src="./main.js"></script>
main.js
import { createGrid } from 'maxgrid';
import { actions, options } from './example';
const api = createGrid(document.getElementById('grid'), options);
document.getElementById('op').addEventListener('change', (event) => actions.op(api, event.target.value));
document.getElementById('footer').addEventListener('change', (event) => actions.footer(api, event.target.value));
example.js
const branches = [
  '서울 본점',
  '강남점',
  '부산점',
  '대구점',
  '인천점',
  '광주점',
  '대전점',
  '제주점',
];
const regions = ['수도권', '수도권', '영남', '영남', '수도권', '호남', '충청', '제주'];
// 단위는 백만원이에요. 지점마다 1~6월 매출이 있어요.
const sales = (i, k) => 20 + ((i * 13 + k * 7) % 70);
const rows = branches.map((branch, i) => ({
  id: i + 1,
  branch,
  region: regions[i],
  m1: sales(i, 1),
  m2: sales(i, 2),
  m3: sales(i, 3),
  m4: sales(i, 4),
  m5: sales(i, 5),
  m6: sales(i, 6),
}));
const months = ['m1', 'm2', 'm3', 'm4', 'm5', 'm6'];
const money = (value) => Number(value).toLocaleString('ko-KR');
const labels = {
  sum: '합계',
  avg: '평균',
  min: '최소',
  max: '최대',
  count: '개수',
};
let op = 'sum';
// 컬럼에 aggregate를 주면 그 컬럼의 값들을 모아서 맨 아래 합계 줄에 계산해 보여 줘요.
// 쓸 수 있는 계산: sum(합계) avg(평균) min(최소) max(최대) count(개수).
const columns = () => [
  { id: 'branch', title: '지점', width: 120 },
  ...months.map((id, k) => ({
    id,
    title: `${k + 1}월`,
    kind: 'number',
    width: 90,
    align: 'end',
    aggregate: op,
    formatValue: money,
    // 평균처럼 소수가 나오는 계산은 한 자리까지만 보여 줘요.
    aggregateFormat: (value) => Number(value).toLocaleString('ko-KR', { maximumFractionDigits: 1 }),
  })),
];
export const options = {
  columns: columns(),
  rows,
  rowKey: 'id',
  summary: { label: labels[op] },
};
export const actions = {
  op: (api, value) => {
    op = (value ?? 'sum');
    api.setColumns(columns());
    api.setOptions({ summary: { label: labels[op] } });
  },
  footer: (api, value) => api.setOptions({ summary: value === 'off' ? false : { label: labels[op] } }),
};

Module files for a project with a bundler such as Vite. To run it with no setup, use the HTML tab or Try it.

When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.

index.html
<div id="app">
  <div class="toolbar">
    <select aria-label="Calculation" id="op">
      <option value="sum" selected>Sum</option>
      <option value="avg">Average</option>
      <option value="min">Minimum</option>
      <option value="max">Maximum</option>
      <option value="count">Count</option>
    </select>
    <select aria-label="Total row" id="footer">
      <option value="on" selected>Show</option>
      <option value="off">Hide</option>
    </select>
  </div>
  <div id="grid" style="height: 360px"></div>
</div>
<script type="module" src="./main.js"></script>
main.js
import { createGrid } from 'maxgrid';
import { actions, options } from './example';
const api = createGrid(document.getElementById('grid'), options);
document.getElementById('op').addEventListener('change', (event) => actions.op(api, event.target.value));
document.getElementById('footer').addEventListener('change', (event) => actions.footer(api, event.target.value));
example.js
const branches = ['Seoul HQ', 'Gangnam', 'Busan', 'Daegu', 'Incheon', 'Gwangju', 'Daejeon', 'Jeju'];
const regions = [
  'Capital',
  'Capital',
  'Yeongnam',
  'Yeongnam',
  'Capital',
  'Honam',
  'Chungcheong',
  'Jeju',
];
// Units are $ thousands. Each branch has sales for January to June.
const sales = (i, k) => 20 + ((i * 13 + k * 7) % 70);
const rows = branches.map((branch, i) => ({
  id: i + 1,
  branch,
  region: regions[i],
  m1: sales(i, 1),
  m2: sales(i, 2),
  m3: sales(i, 3),
  m4: sales(i, 4),
  m5: sales(i, 5),
  m6: sales(i, 6),
}));
const months = ['m1', 'm2', 'm3', 'm4', 'm5', 'm6'];
const money = (value) => Number(value).toLocaleString('en-US');
const labels = {
  sum: 'Total',
  avg: 'Average',
  min: 'Min',
  max: 'Max',
  count: 'Count',
};
let op = 'sum';
// Give a column an aggregate and its values are collected and calculated in the summary row at the bottom.
// Available calculations: sum (total), avg (average), min, max, count.
const columns = () => [
  { id: 'branch', title: 'Branch', width: 120 },
  ...months.map((id, k) => ({
    id,
    title: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'][k],
    kind: 'number',
    width: 90,
    align: 'end',
    aggregate: op,
    formatValue: money,
    // Calculations that produce decimals, such as the average, show one decimal place at most.
    aggregateFormat: (value) => Number(value).toLocaleString('en-US', { maximumFractionDigits: 1 }),
  })),
];
export const options = {
  columns: columns(),
  rows,
  rowKey: 'id',
  summary: { label: labels[op] },
};
export const actions = {
  op: (api, value) => {
    op = (value ?? 'sum');
    api.setColumns(columns());
    api.setOptions({ summary: { label: labels[op] } });
  },
  footer: (api, value) => api.setOptions({ summary: value === 'off' ? false : { label: labels[op] } }),
};