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

고른 칸의 합계와 평균을 바로 보기Instant sum and average of the cells you pick

칸을 끌어서 고르거나 행 번호를 누르면, 고른 칸의 개수·합계·평균·최댓값이 바로 계산돼요. 숫자가 아닌 칸은 알아서 빼고, 나만의 수식도 칸을 읽어서 직접 만들 수 있어요.Drag over cells or click a row number to get the count, sum, average and max of your selection at once. Text cells are skipped, and you can build your own formula from the selected cells.

활용Intermediate
직접 써 보기Live preview고른 칸의 합계와 평균을 바로 보기Instant sum and average of the cells you pick

코드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="formula">
      <option value="basic" selected>합계·평균 (기본)</option>
      <option value="full">합계·평균·최소·최대</option>
      <option value="custom">내 수식: 5,000만 원 넘는 칸</option>
    </select>
    <button type="button" id="pickBlock">블록 고르기</button>
    <button type="button" id="pickRow">대구 행 통째로</button>
    <button type="button" id="pickColumn">3월 열 통째로</button>
    <button type="button" id="clear">선택 지우기</button>
  </div>
  <div id="grid" style="height: 340px"></div>
</div>
<script type="module" src="./main.js"></script>
main.js
import { createGrid } from 'maxgrid';
import { actions, options, setup } from './example';
const api = createGrid(document.getElementById('grid'), options);
setup(api, console.log);
document.getElementById('formula').addEventListener('change', (event) => actions.formula(api, event.target.value));
document.getElementById('pickBlock').addEventListener('click', () => actions.pickBlock(api));
document.getElementById('pickRow').addEventListener('click', () => actions.pickRow(api));
document.getElementById('pickColumn').addEventListener('click', () => actions.pickColumn(api));
document.getElementById('clear').addEventListener('click', () => actions.clear(api));
example.js
// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko, en) => document.documentElement.dataset.lang === 'en' ? en : ko;
const regions = ['서울', '부산', '대구', '인천', '광주', '대전', '울산', '제주'];
const MONTHS = ['m1', 'm2', 'm3', 'm4', 'm5', 'm6'];
// 지역별 월 매출(만 원). 칸을 고르면 그 칸들의 합계·평균·개수를 계산해서 알려 줘요.
// 숫자가 아닌 칸('비고')은 개수에는 들어가지만 합계에는 더하지 않아요.
export const options = {
  columns: [
    { id: 'region', title: '지역', width: 100 },
    ...MONTHS.map((id, i) => ({
      id,
      title: `${i + 1}월`,
      kind: 'number',
      width: 96,
      align: 'end',
      formatValue: (value) => Number(value).toLocaleString('ko-KR'),
    })),
    { id: 'note', title: '비고', width: 140 },
  ],
  rows: regions.map((region, i) => ({
    id: i + 1,
    region,
    m1: 3700 + ((i * 910) % 6000),
    m2: 1700 + ((i * 1230) % 8000),
    m3: 1100 + ((i * 570) % 5000),
    m4: 2900 + ((i * 2130) % 9000),
    m5: 2400 + ((i * 780) % 6500),
    m6: 3100 + ((i * 1470) % 7000),
    note: i % 3 === 0 ? '목표 초과' : '',
  })),
  rowKey: 'id',
  // 왼쪽 행 번호를 누르면 그 행 전체가 선택돼요(Shift는 행 범위, Ctrl은 더하기).
  showRowNumbers: true,
  cellSelection: 'multiple',
};
const won = (n) => n === null ? '-' : `${Math.round(n).toLocaleString('ko-KR')}만원`;
let formula = 'basic';
let say = () => { };
// 고른 칸을 읽어 한 줄 요약을 만들어요. getCellStats()가 기본 계산을 해 주고,
// 나만의 수식은 getSelectedCells()로 칸을 하나씩 읽어서 직접 계산해요.
function summarize(api) {
  const cells = api.getSelectedCells();
  if (cells.length === 0)
    return L('고른 칸이 없어요. 칸을 끌거나 왼쪽 행 번호를 눌러 보세요', 'No cells selected. Drag across cells or click a row number on the left');
  const s = api.getCellStats();
  const base = L(`${s.count}칸 선택 (숫자 ${s.numberCount}칸)`, `${s.count} cells selected (${s.numberCount} numeric)`);
  if (formula === 'full') {
    return `${base} · ${L('합계', 'Sum')} ${won(s.sum)} · ${L('평균', 'Average')} ${won(s.average)} · ${L('최소', 'Min')} ${won(s.min)} · ${L('최대', 'Max')} ${won(s.max)}`;
  }
  if (formula === 'custom') {
    // 내 수식: 선택한 칸 중에서 5,000만 원을 넘긴 칸이 몇 개이고, 전체 숫자 칸의 몇 %인지.
    const over = cells.filter((c) => {
      const v = api.getRowByKey(c.rowKey)?.[c.columnId];
      return typeof v === 'number' && v > 5000;
    }).length;
    const pct = s.numberCount === 0 ? 0 : Math.round((over / s.numberCount) * 100);
    return `${base} · ${L(`5,000만 원 넘는 칸 ${over}개`, `${over} cells over 50 million KRW`)} (${pct}%)`;
  }
  return `${base} · ${L('합계', 'Sum')} ${won(s.sum)} · ${L('평균', 'Average')} ${won(s.average)}`;
}
export function setup(api, log) {
  say = log;
  log({
    ko: '칸을 끌어 보세요. 고른 칸의 개수·합계·평균이 여기에 나와요.',
    en: 'Drag across cells. The count, sum and average of the selection appear here.',
  });
  const off = api.on('cellSelectionChanged', () => log(summarize(api)));
  return () => off();
}
export const actions = {
  // 계산 방식을 바꾸면 지금 고른 칸으로 다시 계산해서 보여 줘요.
  formula: (api, value) => {
    formula = value ?? 'basic';
    say(summarize(api));
  },
  // 코드로 고르기: 서울~울산 지역의 2월~4월 칸 묶음
  pickBlock: (api) => api.selectCells({ rowKey: 1, columnId: 'm2' }, { rowKey: 4, columnId: 'm4' }),
  // 행 번호를 누른 것과 같아요: 3번째 행(대구)의 모든 칸.
  pickRow: (api) => api.selectCells({ rowKey: 3, columnId: 'region' }, { rowKey: 3, columnId: 'note' }),
  // 3월 열 전체
  pickColumn: (api) => api.selectCells({ rowKey: 1, columnId: 'm3' }, { rowKey: 8, columnId: 'm3' }),
  clear: (api) => api.clearCellSelection(),
};

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="Formula" id="formula">
      <option value="basic" selected>Sum and average</option>
      <option value="full">Sum, average, min, max</option>
      <option value="custom">Custom: cells over 5,000</option>
    </select>
    <button type="button" id="pickBlock">Pick a block</button>
    <button type="button" id="pickRow">Whole Daegu row</button>
    <button type="button" id="pickColumn">Whole March column</button>
    <button type="button" id="clear">Clear selection</button>
  </div>
  <div id="grid" style="height: 340px"></div>
</div>
<script type="module" src="./main.js"></script>
main.js
import { createGrid } from 'maxgrid';
import { actions, options, setup } from './example';
const api = createGrid(document.getElementById('grid'), options);
setup(api, console.log);
document.getElementById('formula').addEventListener('change', (event) => actions.formula(api, event.target.value));
document.getElementById('pickBlock').addEventListener('click', () => actions.pickBlock(api));
document.getElementById('pickRow').addEventListener('click', () => actions.pickRow(api));
document.getElementById('pickColumn').addEventListener('click', () => actions.pickColumn(api));
document.getElementById('clear').addEventListener('click', () => actions.clear(api));
example.js
const regions = ['Seoul', 'Busan', 'Daegu', 'Incheon', 'Gwangju', 'Daejeon', 'Ulsan', 'Jeju'];
const MONTHS = ['m1', 'm2', 'm3', 'm4', 'm5', 'm6'];
const MONTH_NAMES = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'];
// Monthly sales per region (in $). Select cells and the sum, average and count of those cells are reported.
// Non-numeric cells ('Note') count toward the cell count but are not added to the sum.
export const options = {
  columns: [
    { id: 'region', title: 'Region', width: 100 },
    ...MONTHS.map((id, i) => ({
      id,
      title: MONTH_NAMES[i],
      kind: 'number',
      width: 96,
      align: 'end',
      formatValue: (value) => Number(value).toLocaleString('en-US'),
    })),
    { id: 'note', title: 'Note', width: 140 },
  ],
  rows: regions.map((region, i) => ({
    id: i + 1,
    region,
    m1: 3700 + ((i * 910) % 6000),
    m2: 1700 + ((i * 1230) % 8000),
    m3: 1100 + ((i * 570) % 5000),
    m4: 2900 + ((i * 2130) % 9000),
    m5: 2400 + ((i * 780) % 6500),
    m6: 3100 + ((i * 1470) % 7000),
    note: i % 3 === 0 ? 'Target exceeded' : '',
  })),
  rowKey: 'id',
  // Clicking a row number on the left selects that whole row (Shift for a row range, Ctrl to add).
  showRowNumbers: true,
  cellSelection: 'multiple',
};
const usd = (n) => n === null ? '-' : `$${Math.round(n).toLocaleString('en-US')}`;
let formula = 'basic';
let say = () => { };
// Reads the selected cells and builds a one-line summary. getCellStats() does the basic math,
// and a custom formula reads cells one by one with getSelectedCells().
function summarize(api) {
  const cells = api.getSelectedCells();
  if (cells.length === 0)
    return 'No cells selected. Drag across cells or click a row number on the left';
  const s = api.getCellStats();
  const base = `${s.count} cells selected (${s.numberCount} numeric)`;
  if (formula === 'full') {
    return `${base} · Sum ${usd(s.sum)} · Average ${usd(s.average)} · Min ${usd(s.min)} · Max ${usd(s.max)}`;
  }
  if (formula === 'custom') {
    // Custom formula: how many selected cells exceed $5,000, and what % of all numeric cells that is.
    const over = cells.filter((c) => {
      const v = api.getRowByKey(c.rowKey)?.[c.columnId];
      return typeof v === 'number' && v > 5000;
    }).length;
    const pct = s.numberCount === 0 ? 0 : Math.round((over / s.numberCount) * 100);
    return `${base} · ${over} cells over $5,000 (${pct}%)`;
  }
  return `${base} · Sum ${usd(s.sum)} · Average ${usd(s.average)}`;
}
export function setup(api, log) {
  say = log;
  log('Drag across cells. The count, sum and average of the selection appear here.');
  const off = api.on('cellSelectionChanged', () => log(summarize(api)));
  return () => off();
}
export const actions = {
  // Changing the formula recalculates with the cells selected right now.
  formula: (api, value) => {
    formula = value ?? 'basic';
    say(summarize(api));
  },
  // Select in code: Feb to Apr cells for the first four regions (Seoul to Incheon)
  pickBlock: (api) => api.selectCells({ rowKey: 1, columnId: 'm2' }, { rowKey: 4, columnId: 'm4' }),
  // Same as clicking a row number: every cell of row 3 (Daegu).
  pickRow: (api) => api.selectCells({ rowKey: 3, columnId: 'region' }, { rowKey: 3, columnId: 'note' }),
  // The whole March column
  pickColumn: (api) => api.selectCells({ rowKey: 1, columnId: 'm3' }, { rowKey: 8, columnId: 'm3' }),
  clear: (api) => api.clearCellSelection(),
};