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

엑셀 파일을 읽어 그리드에 넣기Read an Excel file into the grid

api.importXlsx로 xlsx 파일을 읽어 행을 바꾸거나 뒤에 붙여요. 날짜·숫자·불리언이 컬럼 종류에 맞게 들어와요.Read an xlsx file with api.importXlsx and replace or append the rows. Dates, numbers and booleans arrive in the column kinds.

활용Intermediate
직접 써 보기Live preview엑셀 파일을 읽어 그리드에 넣기Read an Excel file into the grid

코드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 탭이나 직접 해보기를 쓰세요.

이 예제는 추가 패키지가 필요해요. 내 컴퓨터에서 돌리려면 npm i maxgrid @maxgrid/export로 설치하세요.

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

index.html
<div id="app">
  <div class="toolbar">
    <button type="button" id="replace">바꾸기</button>
    <button type="button" id="append">뒤에 붙이기</button>
    <button type="button" id="pick">파일 고르기</button>
    <button type="button" id="bad">깨진 파일</button>
  </div>
  <div id="grid" style="height: 320px"></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('replace').addEventListener('click', () => actions.replace(api));
document.getElementById('append').addEventListener('click', () => actions.append(api));
document.getElementById('pick').addEventListener('click', () => actions.pick(api));
document.getElementById('bad').addEventListener('click', () => actions.bad(api));
example.js
import { exportXlsx, withExport } from '@maxgrid/export';
// importXlsx(source)는 xlsx 파일(File·Blob·ArrayBuffer·Uint8Array)을 행으로 읽어 그리드에 넣어요. 날짜 칸은 YYYY-MM-DD 글자로 와요.
export const options = {
  columns: [
    { id: 'id', title: '번호', kind: 'number', width: 70 },
    { id: 'name', title: '이름', width: 140 },
    { id: 'dept', title: '부서', width: 100 },
    { id: 'joined', title: '입사일', kind: 'date', width: 110 },
    { id: 'salary', title: '급여', kind: 'number', width: 100 },
    { id: 'active', title: '재직', kind: 'boolean', width: 70 },
  ],
  rows: [{ id: 0, name: '(예전 행)', dept: '-', joined: null, salary: 0, active: false }],
  rowKey: 'id',
};
const PEOPLE = [
  ['김하늘', '개발'],
  ['이도윤', '운영'],
  ['박서연', '개발'],
  ['최지우', '디자인'],
];
// 읽어 올 샘플 파일은 같은 패키지의 exportXlsx로 그 자리에서 만들어요(머리글이 그리드 제목과 같아요).
function sample(offset) {
  return exportXlsx({
    columns: [
      { id: 'id', title: '번호', kind: 'number' },
      { id: 'name', title: '이름' },
      { id: 'dept', title: '부서' },
      { id: 'joined', title: '입사일', kind: 'date' },
      { id: 'salary', title: '급여', kind: 'number' },
      { id: 'active', title: '재직', kind: 'boolean' },
    ],
    rows: PEOPLE.map(([name, dept], i) => ({
      id: offset + i + 1,
      name,
      dept,
      joined: `2024-0${i + 1}-1${i}`,
      salary: 3200 + i * 350,
      active: i !== 2,
    })),
  });
}
let say = () => { };
let ex;
let appended = 0;
export function setup(api, log) {
  say = log;
  ex = withExport(api);
  log({
    ko: 'api.importXlsx(파일)은 엑셀 파일을 읽어 그리드에 넣고 { count, columns, sheetNames, warnings }를 돌려줘요.',
    en: 'api.importXlsx(file) reads an Excel file into the grid and returns { count, columns, sheetNames, warnings }.',
  });
}
async function run(label, source, mode) {
  try {
    const r = await ex?.importXlsx(source, { mode });
    if (!r)
      return;
    say({
      ko: `${label}: ${r.count}행, 시트 ${r.sheetNames.join(', ')}, 알림 ${r.warnings.length}개`,
      en: `${label}: ${r.count} rows, sheets ${r.sheetNames.join(', ')}, ${r.warnings.length} warnings`,
    });
  }
  catch (error) {
    const code = error.code ?? 'error';
    say({
      ko: `${label}: 읽지 못했어요 [${code}] ${error.message}`,
      en: `${label}: could not read [${code}] ${error.message}`,
    });
  }
}
export const actions = {
  replace: () => run('바꾸기', sample(10), 'replace'),
  append: () => {
    appended += 1;
    return run('뒤에 붙이기', sample(100 * appended), 'append');
  },
  pick: () => {
    const input = document.createElement('input');
    input.type = 'file';
    input.accept = '.xlsx';
    input.onchange = () => {
      const file = input.files?.[0];
      if (file)
        void run(file.name, file, 'replace');
    };
    input.click();
  },
  bad: () => run('깨진 파일', new TextEncoder().encode('not an xlsx file'), 'replace'),
};

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

This example needs an extra package. To run it locally, install with npm i maxgrid @maxgrid/export.

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="replace">Replace</button>
    <button type="button" id="append">Append</button>
    <button type="button" id="pick">Pick a file</button>
    <button type="button" id="bad">Broken file</button>
  </div>
  <div id="grid" style="height: 320px"></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('replace').addEventListener('click', () => actions.replace(api));
document.getElementById('append').addEventListener('click', () => actions.append(api));
document.getElementById('pick').addEventListener('click', () => actions.pick(api));
document.getElementById('bad').addEventListener('click', () => actions.bad(api));
example.js
import { exportXlsx, withExport } from '@maxgrid/export';
// importXlsx(source) reads an xlsx file (File, Blob, ArrayBuffer or Uint8Array) into the grid. Date cells arrive as YYYY-MM-DD text.
export const options = {
  columns: [
    { id: 'id', title: 'No.', kind: 'number', width: 70 },
    { id: 'name', title: 'Name', width: 140 },
    { id: 'dept', title: 'Dept', width: 100 },
    { id: 'joined', title: 'Joined', kind: 'date', width: 110 },
    { id: 'salary', title: 'Salary', kind: 'number', width: 100 },
    { id: 'active', title: 'Active', kind: 'boolean', width: 70 },
  ],
  rows: [{ id: 0, name: '(old row)', dept: '-', joined: null, salary: 0, active: false }],
  rowKey: 'id',
};
const PEOPLE = [
  ['Liam Carter', 'Dev'],
  ['Emma Stone', 'Ops'],
  ['Noah Reed', 'Dev'],
  ['Ava Brooks', 'Design'],
];
// The sample file is built on the spot with exportXlsx from the same package (its headers match the grid titles).
function sample(offset) {
  return exportXlsx({
    columns: [
      { id: 'id', title: 'No.', kind: 'number' },
      { id: 'name', title: 'Name' },
      { id: 'dept', title: 'Dept' },
      { id: 'joined', title: 'Joined', kind: 'date' },
      { id: 'salary', title: 'Salary', kind: 'number' },
      { id: 'active', title: 'Active', kind: 'boolean' },
    ],
    rows: PEOPLE.map(([name, dept], i) => ({
      id: offset + i + 1,
      name,
      dept,
      joined: `2024-0${i + 1}-1${i}`,
      salary: 3200 + i * 350,
      active: i !== 2,
    })),
  });
}
let say = () => { };
let ex;
let appended = 0;
export function setup(api, log) {
  say = log;
  ex = withExport(api);
  log('api.importXlsx(file) reads an Excel file into the grid and returns { count, columns, sheetNames, warnings }.');
}
async function run(label, source, mode) {
  try {
    const r = await ex?.importXlsx(source, { mode });
    if (!r)
      return;
    say(`${label}: ${r.count} rows, sheets ${r.sheetNames.join(', ')}, ${r.warnings.length} warnings`);
  }
  catch (error) {
    const code = error.code ?? 'error';
    say(`${label}: could not read [${code}] ${error.message}`);
  }
}
export const actions = {
  replace: () => run('Replace', sample(10), 'replace'),
  append: () => {
    appended += 1;
    return run('Append', sample(100 * appended), 'append');
  },
  pick: () => {
    const input = document.createElement('input');
    input.type = 'file';
    input.accept = '.xlsx';
    input.onchange = () => {
      const file = input.files?.[0];
      if (file)
        void run(file.name, file, 'replace');
    };
    input.click();
  },
  bad: () => run('Broken file', new TextEncoder().encode('not an xlsx file'), 'replace'),
};