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

셀 값과 목록을 코드로 읽기Read cell values and lists from code

getCellValue, getCellText로 칸의 값과 화면 글자를, getDistinctValues, findRows로 목록과 행을, getFilteredRowCount, getSummaryText 등으로 개수와 합계 글자를 읽어요. 모두 읽기 전용이고 모르는 키를 줘도 던지지 않아요.Read a cell's value and displayed text with getCellValue and getCellText, lists and rows with getDistinctValues and findRows, and counts and summary text with getFilteredRowCount and getSummaryText. All are read-only and never throw for unknown keys.

활용Intermediate
직접 써 보기Live preview셀 값과 목록을 코드로 읽기Read cell values and lists from code

코드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">
    <button type="button" id="cell">고른 칸 읽기</button>
    <button type="button" id="distinct">팀 목록(정렬)</button>
    <button type="button" id="find">팀이 개발인 행 찾기</button>
    <button type="button" id="filter">영업팀만 걸러 보기</button>
    <button type="button" id="summary">합계 글자 읽기</button>
    <button type="button" id="reset">필터 지우기</button>
  </div>
  <div id="grid" style="height: 440px"></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('cell').addEventListener('click', () => actions.cell(api));
document.getElementById('distinct').addEventListener('click', () => actions.distinct(api));
document.getElementById('find').addEventListener('click', () => actions.find(api));
document.getElementById('filter').addEventListener('click', () => actions.filter(api));
document.getElementById('summary').addEventListener('click', () => actions.summary(api));
document.getElementById('reset').addEventListener('click', () => actions.reset(api));
example.js
const teams = ['개발', '디자인', '영업', '인사'];
const names = ['김민준', '이서연', '박지호', '최유나', '정도윤', '한소희'];
// 값을 읽는 메서드들은 모두 읽기 전용이에요. 모르는 키나 컬럼을 줘도 던지지 않고 undefined, null, 빈 배열을 돌려줘요.
export const options = {
  columns: [
    { id: 'team', title: '팀', width: 90 },
    { id: 'name', title: '이름', width: 100 },
    {
      id: 'amount',
      title: '금액(원)',
      kind: 'number',
      width: 130,
      align: 'end',
      aggregate: 'sum',
      formatValue: (value) => `${Number(value).toLocaleString('ko-KR')}원`,
    },
  ],
  rows: Array.from({ length: 12 }, (_, i) => ({
    id: i + 1,
    team: teams[i % 4],
    name: names[i % 6],
    amount: 120000 + ((i * 37) % 9) * 10000,
  })),
  rowKey: 'id',
  summary: { label: '합계' },
  filterRow: true,
};
let say = () => { };
export function setup(api, log) {
  say = log;
  log({
    ko: '칸을 하나 고른 뒤 아래 버튼을 눌러 보세요. 결과는 이 기록에 나와요.',
    en: 'Select a cell, then press the buttons below. The results show in this log.',
  });
  return () => undefined;
}
export const actions = {
  cell: (api) => {
    const cell = api.getFocusedCell();
    if (cell === null) {
      return say({ ko: '먼저 칸을 하나 골라 주세요.', en: 'Select a cell first.' });
    }
    const value = api.getCellValue(cell.rowKey, cell.columnId);
    const text = api.getCellText(cell.rowKey, cell.columnId);
    say({
      ko: `${cell.rowKey}번 행 ${cell.columnId}: 값 ${String(value)}, 화면에 보이는 글자 "${text}"`,
      en: `Row ${cell.rowKey} ${cell.columnId}: value ${String(value)}, displayed text "${text}"`,
    });
  },
  distinct: (api) => {
    const list = api.getDistinctValues('team', { sort: 'asc' }).join(', ');
    say({ ko: `팀 목록(정렬): ${list}`, en: `Teams (sorted): ${list}` });
  },
  find: (api) => {
    const rows = api.findRows({ team: '개발' });
    say({
      ko: `팀이 개발인 행 ${rows.length}개: ${rows.map((r) => r.name).join(', ')}`,
      en: `${rows.length} rows in team 개발: ${rows.map((r) => r.name).join(', ')}`,
    });
  },
  filter: (api) => {
    api.setColumnFilter('team', [{ columnId: 'team', operator: 'equals', value: '영업' }]);
    say({
      ko: `필터 통과 ${api.getFilteredRowCount()}행, 화면 줄 ${api.getVisibleRowCount()}줄(합계 줄 포함), 필터 걸림: ${String(api.isFilterActive())}`,
      en: `${api.getFilteredRowCount()} rows pass the filter, ${api.getVisibleRowCount()} lines on screen (including the summary), filter active: ${String(api.isFilterActive())}`,
    });
  },
  summary: (api) => {
    say({
      ko: `합계 줄의 금액 칸: "${String(api.getSummaryText('amount'))}", 고정 행: ${api.getPinnedRowCount()}개`,
      en: `Summary row amount cell: "${String(api.getSummaryText('amount'))}", pinned rows: ${api.getPinnedRowCount()}`,
    });
  },
  reset: (api) => api.clearColumnFilter('team'),
};

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">
    <button type="button" id="cell">Read selected cell</button>
    <button type="button" id="distinct">Teams (sorted)</button>
    <button type="button" id="find">Find team Dev rows</button>
    <button type="button" id="filter">Filter to team Sales</button>
    <button type="button" id="summary">Read summary text</button>
    <button type="button" id="reset">Clear filter</button>
  </div>
  <div id="grid" style="height: 440px"></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('cell').addEventListener('click', () => actions.cell(api));
document.getElementById('distinct').addEventListener('click', () => actions.distinct(api));
document.getElementById('find').addEventListener('click', () => actions.find(api));
document.getElementById('filter').addEventListener('click', () => actions.filter(api));
document.getElementById('summary').addEventListener('click', () => actions.summary(api));
document.getElementById('reset').addEventListener('click', () => actions.reset(api));
example.js
const teams = ['Dev', 'Design', 'Sales', 'HR'];
const names = [
  'Liam Carter',
  'Emma Stone',
  'Noah Brooks',
  'Olivia Reed',
  'Ethan Hayes',
  'Sophia Lane',
];
// The read methods are all read-only. Unknown keys or columns never throw: you get undefined, null or an empty array.
export const options = {
  columns: [
    { id: 'team', title: 'Team', width: 90 },
    { id: 'name', title: 'Name', width: 120 },
    {
      id: 'amount',
      title: 'Amount (USD)',
      kind: 'number',
      width: 140,
      align: 'end',
      aggregate: 'sum',
      formatValue: (value) => `$${Number(value).toLocaleString('en-US')}`,
    },
  ],
  rows: Array.from({ length: 12 }, (_, i) => ({
    id: i + 1,
    team: teams[i % 4],
    name: names[i % 6],
    amount: 120 + ((i * 37) % 9) * 10,
  })),
  rowKey: 'id',
  summary: { label: 'Total' },
  filterRow: true,
};
let say = () => { };
export function setup(api, log) {
  say = log;
  log('Select a cell, then press the buttons below. The results show in this log.');
  return () => undefined;
}
export const actions = {
  cell: (api) => {
    const cell = api.getFocusedCell();
    if (cell === null) {
      return say('Select a cell first.');
    }
    const value = api.getCellValue(cell.rowKey, cell.columnId);
    const text = api.getCellText(cell.rowKey, cell.columnId);
    say(`Row ${cell.rowKey} ${cell.columnId}: value ${String(value)}, displayed text "${text}"`);
  },
  distinct: (api) => {
    const list = api.getDistinctValues('team', { sort: 'asc' }).join(', ');
    say(`Teams (sorted): ${list}`);
  },
  find: (api) => {
    const rows = api.findRows({ team: 'Dev' });
    say(`${rows.length} rows in team Dev: ${rows.map((r) => r.name).join(', ')}`);
  },
  filter: (api) => {
    api.setColumnFilter('team', [{ columnId: 'team', operator: 'equals', value: 'Sales' }]);
    say(`${api.getFilteredRowCount()} rows pass the filter, ${api.getVisibleRowCount()} lines on screen (including the summary), filter active: ${String(api.isFilterActive())}`);
  },
  summary: (api) => {
    say(`Summary row amount cell: "${String(api.getSummaryText('amount'))}", pinned rows: ${api.getPinnedRowCount()}`);
  },
  reset: (api) => api.clearColumnFilter('team'),
};