엑셀 파일을 읽어 그리드에 넣기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.
코드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)
이 예제는 추가 패키지가 필요해요. 내 컴퓨터에서 돌리려면 npm i maxgrid @maxgrid/export로 설치하세요.
버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
<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>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));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'),
}; 이 HTML은 추가 번들(위 script 태그)도 함께 불러오고 전역 변수로 써요. 별도 설치는 필요 없어요.
<!doctype html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>엑셀 파일을 읽어 그리드에 넣기</title>
</head>
<body>
<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>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.export.min.js"></script>
<script>
const { exportXlsx, withExport } = MaxGridExport;
// importXlsx(source)는 xlsx 파일(File·Blob·ArrayBuffer·Uint8Array)을 행으로 읽어 그리드에 넣어요. 날짜 칸은 YYYY-MM-DD 글자로 와요.
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;
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}`,
});
}
}
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'),
};
options.ariaLabel = "엑셀 파일을 읽어 그리드에 넣기";
const api = MaxGrid.createGrid(document.getElementById('grid'), options);
setup(api, (message) => {
const item = document.createElement('li');
item.textContent =
typeof message === 'string' ? message : navigator.language.startsWith('ko') ? message.ko : message.en;
document.getElementById('log').prepend(item);
});
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));
</script>
</body>
</html> 이 예제는 추가 패키지가 필요해요. 내 컴퓨터에서 돌리려면 npm i @maxgrid/react @maxgrid/export로 설치하세요.
버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
import { useEffect } from 'react';
import { Grid, useGridApi } from '@maxgrid/react';
import { actions, options, setup, type Row } from './example';
export function ExampleGrid() {
const [api, gridRef] = useGridApi<Row>();
useEffect(() => (api ? setup(api, console.log) : undefined), [api]);
return (
<>
<div className="toolbar">
<button
type="button"
disabled={!api}
onClick={() => api && actions.replace(api)}
>바꾸기</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.append(api)}
>뒤에 붙이기</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.pick(api)}
>파일 고르기</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.bad(api)}
>깨진 파일</button>
</div>
<Grid style={{ height: 320 }} ref={gridRef} options={options} />
</>
);
}import { exportXlsx, withExport, type ExportableGridApi } from '@maxgrid/export';
import type { GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
dept: string;
joined: string | null;
salary: number;
active: boolean;
}
// importXlsx(source)는 xlsx 파일(File·Blob·ArrayBuffer·Uint8Array)을 행으로 읽어 그리드에 넣어요. 날짜 칸은 YYYY-MM-DD 글자로 와요.
export const options: GridOptions<Row> = {
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: Array<[string, string]> = [
['김하늘', '개발'],
['이도윤', '운영'],
['박서연', '개발'],
['최지우', '디자인'],
];
// 읽어 올 샘플 파일은 같은 패키지의 exportXlsx로 그 자리에서 만들어요(머리글이 그리드 제목과 같아요).
function sample(offset: number): Uint8Array {
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: (message: LogText) => void = () => {};
let ex: ExportableGridApi<Row> | undefined;
let appended = 0;
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
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: string, source: Uint8Array | File, mode: 'replace' | 'append') {
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 as { code?: string }).code ?? 'error';
say({
ko: `${label}: 읽지 못했어요 [${code}] ${(error as Error).message}`,
en: `${label}: could not read [${code}] ${(error as 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'),
}; 이 예제는 추가 패키지가 필요해요. 내 컴퓨터에서 돌리려면 npm i @maxgrid/vue @maxgrid/export로 설치하세요.
버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
<script setup lang="ts">
import { onBeforeUnmount, shallowRef } from 'vue';
import { Grid, type GridApi } from '@maxgrid/vue';
import { actions, options, setup, type Row } from './example';
const api = shallowRef<GridApi<Row> | null>(null);
let stop: (() => void) | undefined;
function onReady(event: { api: GridApi<Row> }) {
api.value = event.api;
stop = setup(event.api, console.log);
}
onBeforeUnmount(() => stop?.());
</script>
<template>
<div class="toolbar">
<button type="button" :disabled="!api" @click="api && actions.replace(api)">바꾸기</button>
<button type="button" :disabled="!api" @click="api && actions.append(api)">뒤에 붙이기</button>
<button type="button" :disabled="!api" @click="api && actions.pick(api)">파일 고르기</button>
<button type="button" :disabled="!api" @click="api && actions.bad(api)">깨진 파일</button>
</div>
<Grid style="height: 320px" :options="options" @ready="onReady" />
</template>import { exportXlsx, withExport, type ExportableGridApi } from '@maxgrid/export';
import type { GridApi, GridOptions } from '@maxgrid/vue';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
dept: string;
joined: string | null;
salary: number;
active: boolean;
}
// importXlsx(source)는 xlsx 파일(File·Blob·ArrayBuffer·Uint8Array)을 행으로 읽어 그리드에 넣어요. 날짜 칸은 YYYY-MM-DD 글자로 와요.
export const options: GridOptions<Row> = {
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: Array<[string, string]> = [
['김하늘', '개발'],
['이도윤', '운영'],
['박서연', '개발'],
['최지우', '디자인'],
];
// 읽어 올 샘플 파일은 같은 패키지의 exportXlsx로 그 자리에서 만들어요(머리글이 그리드 제목과 같아요).
function sample(offset: number): Uint8Array {
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: (message: LogText) => void = () => {};
let ex: ExportableGridApi<Row> | undefined;
let appended = 0;
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
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: string, source: Uint8Array | File, mode: 'replace' | 'append') {
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 as { code?: string }).code ?? 'error';
say({
ko: `${label}: 읽지 못했어요 [${code}] ${(error as Error).message}`,
en: `${label}: could not read [${code}] ${(error as 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'),
}; 이 예제는 추가 패키지가 필요해요. 내 컴퓨터에서 돌리려면 npm i @maxgrid/angular @maxgrid/export로 설치하세요.
버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
import { Component, OnDestroy } from '@angular/core';
import { GridComponent, isGridEvent, type GridApi, type GridEventMessage } from '@maxgrid/angular';
import { actions, options, setup, type Row } from './example';
@Component({
selector: 'app-example-grid',
standalone: true,
imports: [GridComponent],
template: `
<div class="toolbar">
<button
type="button"
[disabled]="!api"
(click)="api && actions.replace(api)"
>바꾸기</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.append(api)"
>뒤에 붙이기</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.pick(api)"
>파일 고르기</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.bad(api)"
>깨진 파일</button>
</div>
<mx-grid style="height: 320px" [options]="options" [events]="relayed" (gridEvent)="onEvent($event)" />
`,
})
export class ExampleGridComponent implements OnDestroy {
readonly options = options;
readonly actions = actions;
readonly relayed = ['ready'] as const;
api: GridApi<Row> | null = null;
private stop: (() => void) | null = null;
onEvent(event: GridEventMessage<Row>): void {
if (isGridEvent(event, 'ready')) {
this.api = event.payload.api;
this.stop = setup(this.api, console.log);
}
}
ngOnDestroy(): void {
this.stop?.();
}
}import { exportXlsx, withExport, type ExportableGridApi } from '@maxgrid/export';
import type { GridApi, GridOptions } from '@maxgrid/angular';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
dept: string;
joined: string | null;
salary: number;
active: boolean;
}
// importXlsx(source)는 xlsx 파일(File·Blob·ArrayBuffer·Uint8Array)을 행으로 읽어 그리드에 넣어요. 날짜 칸은 YYYY-MM-DD 글자로 와요.
export const options: GridOptions<Row> = {
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: Array<[string, string]> = [
['김하늘', '개발'],
['이도윤', '운영'],
['박서연', '개발'],
['최지우', '디자인'],
];
// 읽어 올 샘플 파일은 같은 패키지의 exportXlsx로 그 자리에서 만들어요(머리글이 그리드 제목과 같아요).
function sample(offset: number): Uint8Array {
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: (message: LogText) => void = () => {};
let ex: ExportableGridApi<Row> | undefined;
let appended = 0;
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
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: string, source: Uint8Array | File, mode: 'replace' | 'append') {
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 as { code?: string }).code ?? 'error';
say({
ko: `${label}: 읽지 못했어요 [${code}] ${(error as Error).message}`,
en: `${label}: could not read [${code}] ${(error as 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'),
}; 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.
<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>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));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'),
};This HTML also loads an extra bundle (the extra script tag above) and uses it as a global. No install is needed.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Read an Excel file into the grid</title>
</head>
<body>
<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>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.export.min.js"></script>
<script>
const { exportXlsx, withExport } = MaxGridExport;
// importXlsx(source) reads an xlsx file (File, Blob, ArrayBuffer or Uint8Array) into the grid. Date cells arrive as YYYY-MM-DD text.
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;
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}`);
}
}
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'),
};
options.ariaLabel = "Read an Excel file into the grid";
const api = MaxGrid.createGrid(document.getElementById('grid'), options);
setup(api, (message) => {
const item = document.createElement('li');
item.textContent =
typeof message === 'string' ? message : navigator.language.startsWith('ko') ? message.ko : message.en;
document.getElementById('log').prepend(item);
});
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));
</script>
</body>
</html> This example needs an extra package. To run it locally, install with npm i @maxgrid/react @maxgrid/export.
When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
import { useEffect } from 'react';
import { Grid, useGridApi } from '@maxgrid/react';
import { actions, options, setup, type Row } from './example';
export function ExampleGrid() {
const [api, gridRef] = useGridApi<Row>();
useEffect(() => (api ? setup(api, console.log) : undefined), [api]);
return (
<>
<div className="toolbar">
<button
type="button"
disabled={!api}
onClick={() => api && actions.replace(api)}
>Replace</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.append(api)}
>Append</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.pick(api)}
>Pick a file</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.bad(api)}
>Broken file</button>
</div>
<Grid style={{ height: 320 }} ref={gridRef} options={options} />
</>
);
}import { exportXlsx, withExport, type ExportableGridApi } from '@maxgrid/export';
import type { GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string;
export interface Row {
id: number;
name: string;
dept: string;
joined: string | null;
salary: number;
active: boolean;
}
// 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: GridOptions<Row> = {
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: Array<[string, string]> = [
['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: number): Uint8Array {
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: (message: LogText) => void = () => {};
let ex: ExportableGridApi<Row> | undefined;
let appended = 0;
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
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: string, source: Uint8Array | File, mode: 'replace' | 'append') {
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 as { code?: string }).code ?? 'error';
say(`${label}: could not read [${code}] ${(error as 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'),
}; This example needs an extra package. To run it locally, install with npm i @maxgrid/vue @maxgrid/export.
When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
<script setup lang="ts">
import { onBeforeUnmount, shallowRef } from 'vue';
import { Grid, type GridApi } from '@maxgrid/vue';
import { actions, options, setup, type Row } from './example';
const api = shallowRef<GridApi<Row> | null>(null);
let stop: (() => void) | undefined;
function onReady(event: { api: GridApi<Row> }) {
api.value = event.api;
stop = setup(event.api, console.log);
}
onBeforeUnmount(() => stop?.());
</script>
<template>
<div class="toolbar">
<button type="button" :disabled="!api" @click="api && actions.replace(api)">Replace</button>
<button type="button" :disabled="!api" @click="api && actions.append(api)">Append</button>
<button type="button" :disabled="!api" @click="api && actions.pick(api)">Pick a file</button>
<button type="button" :disabled="!api" @click="api && actions.bad(api)">Broken file</button>
</div>
<Grid style="height: 320px" :options="options" @ready="onReady" />
</template>import { exportXlsx, withExport, type ExportableGridApi } from '@maxgrid/export';
import type { GridApi, GridOptions } from '@maxgrid/vue';
export type LogText = string;
export interface Row {
id: number;
name: string;
dept: string;
joined: string | null;
salary: number;
active: boolean;
}
// 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: GridOptions<Row> = {
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: Array<[string, string]> = [
['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: number): Uint8Array {
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: (message: LogText) => void = () => {};
let ex: ExportableGridApi<Row> | undefined;
let appended = 0;
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
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: string, source: Uint8Array | File, mode: 'replace' | 'append') {
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 as { code?: string }).code ?? 'error';
say(`${label}: could not read [${code}] ${(error as 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'),
}; This example needs an extra package. To run it locally, install with npm i @maxgrid/angular @maxgrid/export.
When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
import { Component, OnDestroy } from '@angular/core';
import { GridComponent, isGridEvent, type GridApi, type GridEventMessage } from '@maxgrid/angular';
import { actions, options, setup, type Row } from './example';
@Component({
selector: 'app-example-grid',
standalone: true,
imports: [GridComponent],
template: `
<div class="toolbar">
<button
type="button"
[disabled]="!api"
(click)="api && actions.replace(api)"
>Replace</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.append(api)"
>Append</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.pick(api)"
>Pick a file</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.bad(api)"
>Broken file</button>
</div>
<mx-grid style="height: 320px" [options]="options" [events]="relayed" (gridEvent)="onEvent($event)" />
`,
})
export class ExampleGridComponent implements OnDestroy {
readonly options = options;
readonly actions = actions;
readonly relayed = ['ready'] as const;
api: GridApi<Row> | null = null;
private stop: (() => void) | null = null;
onEvent(event: GridEventMessage<Row>): void {
if (isGridEvent(event, 'ready')) {
this.api = event.payload.api;
this.stop = setup(this.api, console.log);
}
}
ngOnDestroy(): void {
this.stop?.();
}
}import { exportXlsx, withExport, type ExportableGridApi } from '@maxgrid/export';
import type { GridApi, GridOptions } from '@maxgrid/angular';
export type LogText = string;
export interface Row {
id: number;
name: string;
dept: string;
joined: string | null;
salary: number;
active: boolean;
}
// 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: GridOptions<Row> = {
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: Array<[string, string]> = [
['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: number): Uint8Array {
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: (message: LogText) => void = () => {};
let ex: ExportableGridApi<Row> | undefined;
let appended = 0;
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
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: string, source: Uint8Array | File, mode: 'replace' | 'append') {
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 as { code?: string }).code ?? 'error';
say(`${label}: could not read [${code}] ${(error as 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'),
};