바뀐 내용만 CSV로 내려받기Download only the changes as CSV
표 전체가 아니라 "바뀐 칸"만 이전 값과 바뀐 값으로 CSV에 적어 내려받아요. 추가·삭제한 줄도 한 줄씩 남아서, 저장하기 전에 검토하거나 나중에 확인할 기록으로 쓸 수 있어요. 엑셀에서 한글이 깨지지 않게 만들어요.Download only the changed cells, with before and after values, as CSV. Added and removed rows get one line each, so the file can be reviewed before saving or kept as an audit trail. A BOM keeps Korean intact in Excel.
코드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)
버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
<div id="app">
<div class="toolbar">
<button type="button" id="add">직원 추가</button>
<button type="button" id="removeSelected">고른 줄 삭제</button>
<button type="button" id="download">CSV 내려받기</button>
<button type="button" id="discard">변경 버리기</button>
</div>
<div id="grid" style="height: 300px"></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('add').addEventListener('click', () => actions.add(api));
document.getElementById('removeSelected').addEventListener('click', () => actions.removeSelected(api));
document.getElementById('download').addEventListener('click', () => actions.download(api));
document.getElementById('discard').addEventListener('click', () => actions.discard(api));const rows = [
{ id: 1, name: '김서연', department: '개발', salary: 4200 },
{ id: 2, name: '이준호', department: '디자인', salary: 3900 },
{ id: 3, name: '박민지', department: '기획', salary: 4100 },
{ id: 4, name: '최도윤', department: '개발', salary: 3800 },
];
let nextId = 100;
let say = () => { };
export const options = {
columns: [
{ id: 'name', title: '이름', width: 110, editable: true },
{ id: 'department', title: '부서', width: 100, editable: true },
{ id: 'salary', title: '월급(만원)', kind: 'number', width: 120, align: 'end', editable: true },
],
rows,
rowKey: 'id',
selection: { mode: 'multiple', checkbox: true },
saveMode: 'batch',
};
const isEn = () => document.documentElement.dataset.lang === 'en';
// CSV의 글자(상태·머리글)와 파일 이름은 페이지 언어를 따라요.
const WORDS = {
ko: {
added: '추가',
modified: '수정',
removed: '삭제',
head: '줄,상태,항목,이전 값,바뀐 값',
file: '변경내역.csv',
},
en: {
added: 'added',
modified: 'modified',
removed: 'deleted',
head: 'Row,Status,Item,Before,After',
file: 'changes.csv',
},
};
const quote = (value) => `"${String(value ?? '').replace(/"/g, '""')}"`;
// 바뀐 칸마다 한 줄씩: 무엇이 어떻게 바뀌었는지 적어요. 추가·삭제한 줄도 한 줄씩 남겨서,
// 저장 전에 검토하거나 감사 기록으로 쓸 수 있는 파일이 돼요.
function changesToCsv(api, en = isEn()) {
const w = WORDS[en ? 'en' : 'ko'];
const title = (id) => api.getColumns().find((c) => c.id === id)?.title ?? id;
const lines = [w.head];
for (const change of api.getChanges()) {
if (change.state !== 'modified' || !change.cells) {
lines.push([
change.key,
w[change.state] ?? change.state,
'',
'',
change.row.name,
]
.map(quote)
.join(','));
continue;
}
for (const cell of change.cells) {
lines.push([change.key, w.modified, title(cell.columnId), cell.oldValue, cell.newValue]
.map(quote)
.join(','));
}
}
return lines.join('\n');
}
export function setup(api, log) {
say = log;
log({
ko: '칸을 몇 개 고친 뒤 "CSV 내려받기"를 눌러 보세요.',
en: 'Edit a few cells, then press "Download CSV".',
});
return api.on('changesCountChanged', ({ count }) => {
const body = (en) => {
const out = changesToCsv(api, en).split('\n').slice(1);
return out.length ? '\n' + out.join('\n') : '';
};
log({
ko: `변경 ${count}줄${body(false)}`,
en: `${count} changed ${count === 1 ? 'row' : 'rows'}${body(true)}`,
});
});
}
export const actions = {
add: (api) => {
nextId += 1;
api.addRows([{ id: nextId, name: '새 직원', department: '개발', salary: 3500 }], 0);
},
removeSelected: (api) => api.removeRows(api.getSelectedKeys()),
// 엑셀이 한글을 깨뜨리지 않도록 파일 맨 앞에 BOM(\uFEFF)을 붙여요.
download: (api) => {
if (!api.getChanges().length)
return say({
ko: '바뀐 것이 없어서 내려받을 내용이 없어요.',
en: 'Nothing changed, so there is nothing to download.',
});
const link = document.createElement('a');
link.href = URL.createObjectURL(new Blob(['\uFEFF', changesToCsv(api)], { type: 'text/csv' }));
link.download = WORDS[isEn() ? 'en' : 'ko'].file;
link.click();
URL.revokeObjectURL(link.href);
say({ ko: '변경내역.csv를 내려받았어요.', en: 'Downloaded changes.csv.' });
},
discard: (api) => api.rollbackChanges(),
};<!doctype html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>바뀐 내용만 CSV로 내려받기</title>
</head>
<body>
<div class="toolbar">
<button type="button" id="add">직원 추가</button>
<button type="button" id="removeSelected">고른 줄 삭제</button>
<button type="button" id="download">CSV 내려받기</button>
<button type="button" id="discard">변경 버리기</button>
</div>
<div id="grid" style="height: 300px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
const rows = [
{ id: 1, name: '김서연', department: '개발', salary: 4200 },
{ id: 2, name: '이준호', department: '디자인', salary: 3900 },
{ id: 3, name: '박민지', department: '기획', salary: 4100 },
{ id: 4, name: '최도윤', department: '개발', salary: 3800 },
];
let nextId = 100;
let say = () => { };
const options = {
columns: [
{ id: 'name', title: '이름', width: 110, editable: true },
{ id: 'department', title: '부서', width: 100, editable: true },
{ id: 'salary', title: '월급(만원)', kind: 'number', width: 120, align: 'end', editable: true },
],
rows,
rowKey: 'id',
selection: { mode: 'multiple', checkbox: true },
saveMode: 'batch',
};
const isEn = () => document.documentElement.dataset.lang === 'en';
// CSV의 글자(상태·머리글)와 파일 이름은 페이지 언어를 따라요.
const WORDS = {
ko: {
added: '추가',
modified: '수정',
removed: '삭제',
head: '줄,상태,항목,이전 값,바뀐 값',
file: '변경내역.csv',
},
en: {
added: 'added',
modified: 'modified',
removed: 'deleted',
head: 'Row,Status,Item,Before,After',
file: 'changes.csv',
},
};
const quote = (value) => `"${String(value ?? '').replace(/"/g, '""')}"`;
// 바뀐 칸마다 한 줄씩: 무엇이 어떻게 바뀌었는지 적어요. 추가·삭제한 줄도 한 줄씩 남겨서,
// 저장 전에 검토하거나 감사 기록으로 쓸 수 있는 파일이 돼요.
function changesToCsv(api, en = isEn()) {
const w = WORDS[en ? 'en' : 'ko'];
const title = (id) => api.getColumns().find((c) => c.id === id)?.title ?? id;
const lines = [w.head];
for (const change of api.getChanges()) {
if (change.state !== 'modified' || !change.cells) {
lines.push([
change.key,
w[change.state] ?? change.state,
'',
'',
change.row.name,
]
.map(quote)
.join(','));
continue;
}
for (const cell of change.cells) {
lines.push([change.key, w.modified, title(cell.columnId), cell.oldValue, cell.newValue]
.map(quote)
.join(','));
}
}
return lines.join('\n');
}
function setup(api, log) {
say = log;
log({
ko: '칸을 몇 개 고친 뒤 "CSV 내려받기"를 눌러 보세요.',
en: 'Edit a few cells, then press "Download CSV".',
});
return api.on('changesCountChanged', ({ count }) => {
const body = (en) => {
const out = changesToCsv(api, en).split('\n').slice(1);
return out.length ? '\n' + out.join('\n') : '';
};
log({
ko: `변경 ${count}줄${body(false)}`,
en: `${count} changed ${count === 1 ? 'row' : 'rows'}${body(true)}`,
});
});
}
const actions = {
add: (api) => {
nextId += 1;
api.addRows([{ id: nextId, name: '새 직원', department: '개발', salary: 3500 }], 0);
},
removeSelected: (api) => api.removeRows(api.getSelectedKeys()),
// 엑셀이 한글을 깨뜨리지 않도록 파일 맨 앞에 BOM(\uFEFF)을 붙여요.
download: (api) => {
if (!api.getChanges().length)
return say({
ko: '바뀐 것이 없어서 내려받을 내용이 없어요.',
en: 'Nothing changed, so there is nothing to download.',
});
const link = document.createElement('a');
link.href = URL.createObjectURL(new Blob(['\uFEFF', changesToCsv(api)], { type: 'text/csv' }));
link.download = WORDS[isEn() ? 'en' : 'ko'].file;
link.click();
URL.revokeObjectURL(link.href);
say({ ko: '변경내역.csv를 내려받았어요.', en: 'Downloaded changes.csv.' });
},
discard: (api) => api.rollbackChanges(),
};
options.ariaLabel = "바뀐 내용만 CSV로 내려받기";
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('add').addEventListener('click', () => actions.add(api));
document.getElementById('removeSelected').addEventListener('click', () => actions.removeSelected(api));
document.getElementById('download').addEventListener('click', () => actions.download(api));
document.getElementById('discard').addEventListener('click', () => actions.discard(api));
</script>
</body>
</html>버튼을 누르면 이 예제의 코드가 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.add(api)}
>직원 추가</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.removeSelected(api)}
>고른 줄 삭제</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.download(api)}
>CSV 내려받기</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.discard(api)}
>변경 버리기</button>
</div>
<Grid style={{ height: 300 }} ref={gridRef} options={options} />
</>
);
}import type { GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
department: string;
salary: number;
}
const rows: Row[] = [
{ id: 1, name: '김서연', department: '개발', salary: 4200 },
{ id: 2, name: '이준호', department: '디자인', salary: 3900 },
{ id: 3, name: '박민지', department: '기획', salary: 4100 },
{ id: 4, name: '최도윤', department: '개발', salary: 3800 },
];
let nextId = 100;
let say: (message: LogText) => void = () => {};
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: '이름', width: 110, editable: true },
{ id: 'department', title: '부서', width: 100, editable: true },
{ id: 'salary', title: '월급(만원)', kind: 'number', width: 120, align: 'end', editable: true },
],
rows,
rowKey: 'id',
selection: { mode: 'multiple', checkbox: true },
saveMode: 'batch',
};
const isEn = (): boolean => document.documentElement.dataset.lang === 'en';
// CSV의 글자(상태·머리글)와 파일 이름은 페이지 언어를 따라요.
const WORDS = {
ko: {
added: '추가',
modified: '수정',
removed: '삭제',
head: '줄,상태,항목,이전 값,바뀐 값',
file: '변경내역.csv',
},
en: {
added: 'added',
modified: 'modified',
removed: 'deleted',
head: 'Row,Status,Item,Before,After',
file: 'changes.csv',
},
} as const;
const quote = (value: unknown): string => `"${String(value ?? '').replace(/"/g, '""')}"`;
// 바뀐 칸마다 한 줄씩: 무엇이 어떻게 바뀌었는지 적어요. 추가·삭제한 줄도 한 줄씩 남겨서,
// 저장 전에 검토하거나 감사 기록으로 쓸 수 있는 파일이 돼요.
function changesToCsv(api: GridApi<Row>, en = isEn()): string {
const w = WORDS[en ? 'en' : 'ko'];
const title = (id: string) => api.getColumns().find((c) => c.id === id)?.title ?? id;
const lines: string[] = [w.head];
for (const change of api.getChanges()) {
if (change.state !== 'modified' || !change.cells) {
lines.push(
[
change.key,
w[change.state as 'added' | 'modified' | 'removed'] ?? change.state,
'',
'',
change.row.name,
]
.map(quote)
.join(','),
);
continue;
}
for (const cell of change.cells) {
lines.push(
[change.key, w.modified, title(cell.columnId), cell.oldValue, cell.newValue]
.map(quote)
.join(','),
);
}
}
return lines.join('\n');
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
log({
ko: '칸을 몇 개 고친 뒤 "CSV 내려받기"를 눌러 보세요.',
en: 'Edit a few cells, then press "Download CSV".',
});
return api.on('changesCountChanged', ({ count }) => {
const body = (en: boolean): string => {
const out = changesToCsv(api, en).split('\n').slice(1);
return out.length ? '\n' + out.join('\n') : '';
};
log({
ko: `변경 ${count}줄${body(false)}`,
en: `${count} changed ${count === 1 ? 'row' : 'rows'}${body(true)}`,
});
});
}
export const actions = {
add: (api: GridApi<Row>) => {
nextId += 1;
api.addRows([{ id: nextId, name: '새 직원', department: '개발', salary: 3500 }], 0);
},
removeSelected: (api: GridApi<Row>) => api.removeRows(api.getSelectedKeys()),
// 엑셀이 한글을 깨뜨리지 않도록 파일 맨 앞에 BOM(\uFEFF)을 붙여요.
download: (api: GridApi<Row>) => {
if (!api.getChanges().length)
return say({
ko: '바뀐 것이 없어서 내려받을 내용이 없어요.',
en: 'Nothing changed, so there is nothing to download.',
});
const link = document.createElement('a');
link.href = URL.createObjectURL(new Blob(['\uFEFF', changesToCsv(api)], { type: 'text/csv' }));
link.download = WORDS[isEn() ? 'en' : 'ko'].file;
link.click();
URL.revokeObjectURL(link.href);
say({ ko: '변경내역.csv를 내려받았어요.', en: 'Downloaded changes.csv.' });
},
discard: (api: GridApi<Row>) => api.rollbackChanges(),
};버튼을 누르면 이 예제의 코드가 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.add(api)">직원 추가</button>
<button
type="button"
:disabled="!api"
@click="api && actions.removeSelected(api)"
>고른 줄 삭제</button>
<button
type="button"
:disabled="!api"
@click="api && actions.download(api)"
>CSV 내려받기</button>
<button type="button" :disabled="!api" @click="api && actions.discard(api)">변경 버리기</button>
</div>
<Grid style="height: 300px" :options="options" @ready="onReady" />
</template>import type { GridApi, GridOptions } from '@maxgrid/vue';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
department: string;
salary: number;
}
const rows: Row[] = [
{ id: 1, name: '김서연', department: '개발', salary: 4200 },
{ id: 2, name: '이준호', department: '디자인', salary: 3900 },
{ id: 3, name: '박민지', department: '기획', salary: 4100 },
{ id: 4, name: '최도윤', department: '개발', salary: 3800 },
];
let nextId = 100;
let say: (message: LogText) => void = () => {};
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: '이름', width: 110, editable: true },
{ id: 'department', title: '부서', width: 100, editable: true },
{ id: 'salary', title: '월급(만원)', kind: 'number', width: 120, align: 'end', editable: true },
],
rows,
rowKey: 'id',
selection: { mode: 'multiple', checkbox: true },
saveMode: 'batch',
};
const isEn = (): boolean => document.documentElement.dataset.lang === 'en';
// CSV의 글자(상태·머리글)와 파일 이름은 페이지 언어를 따라요.
const WORDS = {
ko: {
added: '추가',
modified: '수정',
removed: '삭제',
head: '줄,상태,항목,이전 값,바뀐 값',
file: '변경내역.csv',
},
en: {
added: 'added',
modified: 'modified',
removed: 'deleted',
head: 'Row,Status,Item,Before,After',
file: 'changes.csv',
},
} as const;
const quote = (value: unknown): string => `"${String(value ?? '').replace(/"/g, '""')}"`;
// 바뀐 칸마다 한 줄씩: 무엇이 어떻게 바뀌었는지 적어요. 추가·삭제한 줄도 한 줄씩 남겨서,
// 저장 전에 검토하거나 감사 기록으로 쓸 수 있는 파일이 돼요.
function changesToCsv(api: GridApi<Row>, en = isEn()): string {
const w = WORDS[en ? 'en' : 'ko'];
const title = (id: string) => api.getColumns().find((c) => c.id === id)?.title ?? id;
const lines: string[] = [w.head];
for (const change of api.getChanges()) {
if (change.state !== 'modified' || !change.cells) {
lines.push(
[
change.key,
w[change.state as 'added' | 'modified' | 'removed'] ?? change.state,
'',
'',
change.row.name,
]
.map(quote)
.join(','),
);
continue;
}
for (const cell of change.cells) {
lines.push(
[change.key, w.modified, title(cell.columnId), cell.oldValue, cell.newValue]
.map(quote)
.join(','),
);
}
}
return lines.join('\n');
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
log({
ko: '칸을 몇 개 고친 뒤 "CSV 내려받기"를 눌러 보세요.',
en: 'Edit a few cells, then press "Download CSV".',
});
return api.on('changesCountChanged', ({ count }) => {
const body = (en: boolean): string => {
const out = changesToCsv(api, en).split('\n').slice(1);
return out.length ? '\n' + out.join('\n') : '';
};
log({
ko: `변경 ${count}줄${body(false)}`,
en: `${count} changed ${count === 1 ? 'row' : 'rows'}${body(true)}`,
});
});
}
export const actions = {
add: (api: GridApi<Row>) => {
nextId += 1;
api.addRows([{ id: nextId, name: '새 직원', department: '개발', salary: 3500 }], 0);
},
removeSelected: (api: GridApi<Row>) => api.removeRows(api.getSelectedKeys()),
// 엑셀이 한글을 깨뜨리지 않도록 파일 맨 앞에 BOM(\uFEFF)을 붙여요.
download: (api: GridApi<Row>) => {
if (!api.getChanges().length)
return say({
ko: '바뀐 것이 없어서 내려받을 내용이 없어요.',
en: 'Nothing changed, so there is nothing to download.',
});
const link = document.createElement('a');
link.href = URL.createObjectURL(new Blob(['\uFEFF', changesToCsv(api)], { type: 'text/csv' }));
link.download = WORDS[isEn() ? 'en' : 'ko'].file;
link.click();
URL.revokeObjectURL(link.href);
say({ ko: '변경내역.csv를 내려받았어요.', en: 'Downloaded changes.csv.' });
},
discard: (api: GridApi<Row>) => api.rollbackChanges(),
};버튼을 누르면 이 예제의 코드가 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.add(api)"
>직원 추가</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.removeSelected(api)"
>고른 줄 삭제</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.download(api)"
>CSV 내려받기</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.discard(api)"
>변경 버리기</button>
</div>
<mx-grid style="height: 300px" [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 type { GridApi, GridOptions } from '@maxgrid/angular';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
department: string;
salary: number;
}
const rows: Row[] = [
{ id: 1, name: '김서연', department: '개발', salary: 4200 },
{ id: 2, name: '이준호', department: '디자인', salary: 3900 },
{ id: 3, name: '박민지', department: '기획', salary: 4100 },
{ id: 4, name: '최도윤', department: '개발', salary: 3800 },
];
let nextId = 100;
let say: (message: LogText) => void = () => {};
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: '이름', width: 110, editable: true },
{ id: 'department', title: '부서', width: 100, editable: true },
{ id: 'salary', title: '월급(만원)', kind: 'number', width: 120, align: 'end', editable: true },
],
rows,
rowKey: 'id',
selection: { mode: 'multiple', checkbox: true },
saveMode: 'batch',
};
const isEn = (): boolean => document.documentElement.dataset.lang === 'en';
// CSV의 글자(상태·머리글)와 파일 이름은 페이지 언어를 따라요.
const WORDS = {
ko: {
added: '추가',
modified: '수정',
removed: '삭제',
head: '줄,상태,항목,이전 값,바뀐 값',
file: '변경내역.csv',
},
en: {
added: 'added',
modified: 'modified',
removed: 'deleted',
head: 'Row,Status,Item,Before,After',
file: 'changes.csv',
},
} as const;
const quote = (value: unknown): string => `"${String(value ?? '').replace(/"/g, '""')}"`;
// 바뀐 칸마다 한 줄씩: 무엇이 어떻게 바뀌었는지 적어요. 추가·삭제한 줄도 한 줄씩 남겨서,
// 저장 전에 검토하거나 감사 기록으로 쓸 수 있는 파일이 돼요.
function changesToCsv(api: GridApi<Row>, en = isEn()): string {
const w = WORDS[en ? 'en' : 'ko'];
const title = (id: string) => api.getColumns().find((c) => c.id === id)?.title ?? id;
const lines: string[] = [w.head];
for (const change of api.getChanges()) {
if (change.state !== 'modified' || !change.cells) {
lines.push(
[
change.key,
w[change.state as 'added' | 'modified' | 'removed'] ?? change.state,
'',
'',
change.row.name,
]
.map(quote)
.join(','),
);
continue;
}
for (const cell of change.cells) {
lines.push(
[change.key, w.modified, title(cell.columnId), cell.oldValue, cell.newValue]
.map(quote)
.join(','),
);
}
}
return lines.join('\n');
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
log({
ko: '칸을 몇 개 고친 뒤 "CSV 내려받기"를 눌러 보세요.',
en: 'Edit a few cells, then press "Download CSV".',
});
return api.on('changesCountChanged', ({ count }) => {
const body = (en: boolean): string => {
const out = changesToCsv(api, en).split('\n').slice(1);
return out.length ? '\n' + out.join('\n') : '';
};
log({
ko: `변경 ${count}줄${body(false)}`,
en: `${count} changed ${count === 1 ? 'row' : 'rows'}${body(true)}`,
});
});
}
export const actions = {
add: (api: GridApi<Row>) => {
nextId += 1;
api.addRows([{ id: nextId, name: '새 직원', department: '개발', salary: 3500 }], 0);
},
removeSelected: (api: GridApi<Row>) => api.removeRows(api.getSelectedKeys()),
// 엑셀이 한글을 깨뜨리지 않도록 파일 맨 앞에 BOM(\uFEFF)을 붙여요.
download: (api: GridApi<Row>) => {
if (!api.getChanges().length)
return say({
ko: '바뀐 것이 없어서 내려받을 내용이 없어요.',
en: 'Nothing changed, so there is nothing to download.',
});
const link = document.createElement('a');
link.href = URL.createObjectURL(new Blob(['\uFEFF', changesToCsv(api)], { type: 'text/csv' }));
link.download = WORDS[isEn() ? 'en' : 'ko'].file;
link.click();
URL.revokeObjectURL(link.href);
say({ ko: '변경내역.csv를 내려받았어요.', en: 'Downloaded changes.csv.' });
},
discard: (api: GridApi<Row>) => api.rollbackChanges(),
};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="add">Add employee</button>
<button type="button" id="removeSelected">Delete selected</button>
<button type="button" id="download">Download CSV</button>
<button type="button" id="discard">Discard changes</button>
</div>
<div id="grid" style="height: 300px"></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('add').addEventListener('click', () => actions.add(api));
document.getElementById('removeSelected').addEventListener('click', () => actions.removeSelected(api));
document.getElementById('download').addEventListener('click', () => actions.download(api));
document.getElementById('discard').addEventListener('click', () => actions.discard(api));const rows = [
{ id: 1, name: 'Liam Carter', department: 'Dev', salary: 42000 },
{ id: 2, name: 'Emma Stone', department: 'Design', salary: 39000 },
{ id: 3, name: 'Noah Kim', department: 'Planning', salary: 41000 },
{ id: 4, name: 'Olivia Park', department: 'Dev', salary: 38000 },
];
let nextId = 100;
let say = () => { };
export const options = {
columns: [
{ id: 'name', title: 'Name', width: 110, editable: true },
{ id: 'department', title: 'Department', width: 100, editable: true },
{ id: 'salary', title: 'Salary ($)', kind: 'number', width: 120, align: 'end', editable: true },
],
rows,
rowKey: 'id',
selection: { mode: 'multiple', checkbox: true },
saveMode: 'batch',
};
// The CSV text (status, header) and the file name are fixed to English.
const WORDS = {
added: 'added',
modified: 'modified',
removed: 'deleted',
head: 'Row,Status,Item,Before,After',
file: 'changes.csv',
};
const quote = (value) => `"${String(value ?? '').replace(/"/g, '""')}"`;
// One line per changed cell: it records what changed and how. Added and deleted rows also get one line each,
// so the file can be reviewed before saving or kept as an audit record.
function changesToCsv(api) {
const w = WORDS;
const title = (id) => api.getColumns().find((c) => c.id === id)?.title ?? id;
const lines = [w.head];
for (const change of api.getChanges()) {
if (change.state !== 'modified' || !change.cells) {
lines.push([
change.key,
w[change.state] ?? change.state,
'',
'',
change.row.name,
]
.map(quote)
.join(','));
continue;
}
for (const cell of change.cells) {
lines.push([change.key, w.modified, title(cell.columnId), cell.oldValue, cell.newValue]
.map(quote)
.join(','));
}
}
return lines.join('\n');
}
export function setup(api, log) {
say = log;
log('Edit a few cells, then press "Download CSV".');
return api.on('changesCountChanged', ({ count }) => {
const body = () => {
const out = changesToCsv(api).split('\n').slice(1);
return out.length ? '\n' + out.join('\n') : '';
};
log(`${count} changed ${count === 1 ? 'row' : 'rows'}${body()}`);
});
}
export const actions = {
add: (api) => {
nextId += 1;
api.addRows([{ id: nextId, name: 'New hire', department: 'Dev', salary: 35000 }], 0);
},
removeSelected: (api) => api.removeRows(api.getSelectedKeys()),
// Put a BOM (\uFEFF) at the start of the file so Excel reads the encoding correctly.
download: (api) => {
if (!api.getChanges().length)
return say('Nothing changed, so there is nothing to download.');
const link = document.createElement('a');
link.href = URL.createObjectURL(new Blob(['\uFEFF', changesToCsv(api)], { type: 'text/csv' }));
link.download = WORDS.file;
link.click();
URL.revokeObjectURL(link.href);
say('Downloaded changes.csv.');
},
discard: (api) => api.rollbackChanges(),
};<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Download only the changes as CSV</title>
</head>
<body>
<div class="toolbar">
<button type="button" id="add">Add employee</button>
<button type="button" id="removeSelected">Delete selected</button>
<button type="button" id="download">Download CSV</button>
<button type="button" id="discard">Discard changes</button>
</div>
<div id="grid" style="height: 300px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
const rows = [
{ id: 1, name: 'Liam Carter', department: 'Dev', salary: 42000 },
{ id: 2, name: 'Emma Stone', department: 'Design', salary: 39000 },
{ id: 3, name: 'Noah Kim', department: 'Planning', salary: 41000 },
{ id: 4, name: 'Olivia Park', department: 'Dev', salary: 38000 },
];
let nextId = 100;
let say = () => { };
const options = {
columns: [
{ id: 'name', title: 'Name', width: 110, editable: true },
{ id: 'department', title: 'Department', width: 100, editable: true },
{ id: 'salary', title: 'Salary ($)', kind: 'number', width: 120, align: 'end', editable: true },
],
rows,
rowKey: 'id',
selection: { mode: 'multiple', checkbox: true },
saveMode: 'batch',
};
// The CSV text (status, header) and the file name are fixed to English.
const WORDS = {
added: 'added',
modified: 'modified',
removed: 'deleted',
head: 'Row,Status,Item,Before,After',
file: 'changes.csv',
};
const quote = (value) => `"${String(value ?? '').replace(/"/g, '""')}"`;
// One line per changed cell: it records what changed and how. Added and deleted rows also get one line each,
// so the file can be reviewed before saving or kept as an audit record.
function changesToCsv(api) {
const w = WORDS;
const title = (id) => api.getColumns().find((c) => c.id === id)?.title ?? id;
const lines = [w.head];
for (const change of api.getChanges()) {
if (change.state !== 'modified' || !change.cells) {
lines.push([
change.key,
w[change.state] ?? change.state,
'',
'',
change.row.name,
]
.map(quote)
.join(','));
continue;
}
for (const cell of change.cells) {
lines.push([change.key, w.modified, title(cell.columnId), cell.oldValue, cell.newValue]
.map(quote)
.join(','));
}
}
return lines.join('\n');
}
function setup(api, log) {
say = log;
log('Edit a few cells, then press "Download CSV".');
return api.on('changesCountChanged', ({ count }) => {
const body = () => {
const out = changesToCsv(api).split('\n').slice(1);
return out.length ? '\n' + out.join('\n') : '';
};
log(`${count} changed ${count === 1 ? 'row' : 'rows'}${body()}`);
});
}
const actions = {
add: (api) => {
nextId += 1;
api.addRows([{ id: nextId, name: 'New hire', department: 'Dev', salary: 35000 }], 0);
},
removeSelected: (api) => api.removeRows(api.getSelectedKeys()),
// Put a BOM (\uFEFF) at the start of the file so Excel reads the encoding correctly.
download: (api) => {
if (!api.getChanges().length)
return say('Nothing changed, so there is nothing to download.');
const link = document.createElement('a');
link.href = URL.createObjectURL(new Blob(['\uFEFF', changesToCsv(api)], { type: 'text/csv' }));
link.download = WORDS.file;
link.click();
URL.revokeObjectURL(link.href);
say('Downloaded changes.csv.');
},
discard: (api) => api.rollbackChanges(),
};
options.ariaLabel = "Download only the changes as CSV";
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('add').addEventListener('click', () => actions.add(api));
document.getElementById('removeSelected').addEventListener('click', () => actions.removeSelected(api));
document.getElementById('download').addEventListener('click', () => actions.download(api));
document.getElementById('discard').addEventListener('click', () => actions.discard(api));
</script>
</body>
</html>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.add(api)}
>Add employee</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.removeSelected(api)}
>Delete selected</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.download(api)}
>Download CSV</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.discard(api)}
>Discard changes</button>
</div>
<Grid style={{ height: 300 }} ref={gridRef} options={options} />
</>
);
}import type { GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
department: string;
salary: number;
}
const rows: Row[] = [
{ id: 1, name: 'Liam Carter', department: 'Dev', salary: 42000 },
{ id: 2, name: 'Emma Stone', department: 'Design', salary: 39000 },
{ id: 3, name: 'Noah Kim', department: 'Planning', salary: 41000 },
{ id: 4, name: 'Olivia Park', department: 'Dev', salary: 38000 },
];
let nextId = 100;
let say: (message: LogText) => void = () => {};
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: 'Name', width: 110, editable: true },
{ id: 'department', title: 'Department', width: 100, editable: true },
{ id: 'salary', title: 'Salary ($)', kind: 'number', width: 120, align: 'end', editable: true },
],
rows,
rowKey: 'id',
selection: { mode: 'multiple', checkbox: true },
saveMode: 'batch',
};
// The CSV text (status, header) and the file name are fixed to English.
const WORDS = {
added: 'added',
modified: 'modified',
removed: 'deleted',
head: 'Row,Status,Item,Before,After',
file: 'changes.csv',
} as const;
const quote = (value: unknown): string => `"${String(value ?? '').replace(/"/g, '""')}"`;
// One line per changed cell: it records what changed and how. Added and deleted rows also get one line each,
// so the file can be reviewed before saving or kept as an audit record.
function changesToCsv(api: GridApi<Row>): string {
const w = WORDS;
const title = (id: string) => api.getColumns().find((c) => c.id === id)?.title ?? id;
const lines: string[] = [w.head];
for (const change of api.getChanges()) {
if (change.state !== 'modified' || !change.cells) {
lines.push(
[
change.key,
w[change.state as 'added' | 'modified' | 'removed'] ?? change.state,
'',
'',
change.row.name,
]
.map(quote)
.join(','),
);
continue;
}
for (const cell of change.cells) {
lines.push(
[change.key, w.modified, title(cell.columnId), cell.oldValue, cell.newValue]
.map(quote)
.join(','),
);
}
}
return lines.join('\n');
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
log('Edit a few cells, then press "Download CSV".');
return api.on('changesCountChanged', ({ count }) => {
const body = (): string => {
const out = changesToCsv(api).split('\n').slice(1);
return out.length ? '\n' + out.join('\n') : '';
};
log(`${count} changed ${count === 1 ? 'row' : 'rows'}${body()}`);
});
}
export const actions = {
add: (api: GridApi<Row>) => {
nextId += 1;
api.addRows([{ id: nextId, name: 'New hire', department: 'Dev', salary: 35000 }], 0);
},
removeSelected: (api: GridApi<Row>) => api.removeRows(api.getSelectedKeys()),
// Put a BOM (\uFEFF) at the start of the file so Excel reads the encoding correctly.
download: (api: GridApi<Row>) => {
if (!api.getChanges().length) return say('Nothing changed, so there is nothing to download.');
const link = document.createElement('a');
link.href = URL.createObjectURL(new Blob(['\uFEFF', changesToCsv(api)], { type: 'text/csv' }));
link.download = WORDS.file;
link.click();
URL.revokeObjectURL(link.href);
say('Downloaded changes.csv.');
},
discard: (api: GridApi<Row>) => api.rollbackChanges(),
};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.add(api)">Add employee</button>
<button
type="button"
:disabled="!api"
@click="api && actions.removeSelected(api)"
>Delete selected</button>
<button
type="button"
:disabled="!api"
@click="api && actions.download(api)"
>Download CSV</button>
<button type="button" :disabled="!api" @click="api && actions.discard(api)">Discard changes</button>
</div>
<Grid style="height: 300px" :options="options" @ready="onReady" />
</template>import type { GridApi, GridOptions } from '@maxgrid/vue';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
department: string;
salary: number;
}
const rows: Row[] = [
{ id: 1, name: 'Liam Carter', department: 'Dev', salary: 42000 },
{ id: 2, name: 'Emma Stone', department: 'Design', salary: 39000 },
{ id: 3, name: 'Noah Kim', department: 'Planning', salary: 41000 },
{ id: 4, name: 'Olivia Park', department: 'Dev', salary: 38000 },
];
let nextId = 100;
let say: (message: LogText) => void = () => {};
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: 'Name', width: 110, editable: true },
{ id: 'department', title: 'Department', width: 100, editable: true },
{ id: 'salary', title: 'Salary ($)', kind: 'number', width: 120, align: 'end', editable: true },
],
rows,
rowKey: 'id',
selection: { mode: 'multiple', checkbox: true },
saveMode: 'batch',
};
// The CSV text (status, header) and the file name are fixed to English.
const WORDS = {
added: 'added',
modified: 'modified',
removed: 'deleted',
head: 'Row,Status,Item,Before,After',
file: 'changes.csv',
} as const;
const quote = (value: unknown): string => `"${String(value ?? '').replace(/"/g, '""')}"`;
// One line per changed cell: it records what changed and how. Added and deleted rows also get one line each,
// so the file can be reviewed before saving or kept as an audit record.
function changesToCsv(api: GridApi<Row>): string {
const w = WORDS;
const title = (id: string) => api.getColumns().find((c) => c.id === id)?.title ?? id;
const lines: string[] = [w.head];
for (const change of api.getChanges()) {
if (change.state !== 'modified' || !change.cells) {
lines.push(
[
change.key,
w[change.state as 'added' | 'modified' | 'removed'] ?? change.state,
'',
'',
change.row.name,
]
.map(quote)
.join(','),
);
continue;
}
for (const cell of change.cells) {
lines.push(
[change.key, w.modified, title(cell.columnId), cell.oldValue, cell.newValue]
.map(quote)
.join(','),
);
}
}
return lines.join('\n');
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
log('Edit a few cells, then press "Download CSV".');
return api.on('changesCountChanged', ({ count }) => {
const body = (): string => {
const out = changesToCsv(api).split('\n').slice(1);
return out.length ? '\n' + out.join('\n') : '';
};
log(`${count} changed ${count === 1 ? 'row' : 'rows'}${body()}`);
});
}
export const actions = {
add: (api: GridApi<Row>) => {
nextId += 1;
api.addRows([{ id: nextId, name: 'New hire', department: 'Dev', salary: 35000 }], 0);
},
removeSelected: (api: GridApi<Row>) => api.removeRows(api.getSelectedKeys()),
// Put a BOM (\uFEFF) at the start of the file so Excel reads the encoding correctly.
download: (api: GridApi<Row>) => {
if (!api.getChanges().length) return say('Nothing changed, so there is nothing to download.');
const link = document.createElement('a');
link.href = URL.createObjectURL(new Blob(['\uFEFF', changesToCsv(api)], { type: 'text/csv' }));
link.download = WORDS.file;
link.click();
URL.revokeObjectURL(link.href);
say('Downloaded changes.csv.');
},
discard: (api: GridApi<Row>) => api.rollbackChanges(),
};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.add(api)"
>Add employee</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.removeSelected(api)"
>Delete selected</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.download(api)"
>Download CSV</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.discard(api)"
>Discard changes</button>
</div>
<mx-grid style="height: 300px" [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 type { GridApi, GridOptions } from '@maxgrid/angular';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
department: string;
salary: number;
}
const rows: Row[] = [
{ id: 1, name: 'Liam Carter', department: 'Dev', salary: 42000 },
{ id: 2, name: 'Emma Stone', department: 'Design', salary: 39000 },
{ id: 3, name: 'Noah Kim', department: 'Planning', salary: 41000 },
{ id: 4, name: 'Olivia Park', department: 'Dev', salary: 38000 },
];
let nextId = 100;
let say: (message: LogText) => void = () => {};
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: 'Name', width: 110, editable: true },
{ id: 'department', title: 'Department', width: 100, editable: true },
{ id: 'salary', title: 'Salary ($)', kind: 'number', width: 120, align: 'end', editable: true },
],
rows,
rowKey: 'id',
selection: { mode: 'multiple', checkbox: true },
saveMode: 'batch',
};
// The CSV text (status, header) and the file name are fixed to English.
const WORDS = {
added: 'added',
modified: 'modified',
removed: 'deleted',
head: 'Row,Status,Item,Before,After',
file: 'changes.csv',
} as const;
const quote = (value: unknown): string => `"${String(value ?? '').replace(/"/g, '""')}"`;
// One line per changed cell: it records what changed and how. Added and deleted rows also get one line each,
// so the file can be reviewed before saving or kept as an audit record.
function changesToCsv(api: GridApi<Row>): string {
const w = WORDS;
const title = (id: string) => api.getColumns().find((c) => c.id === id)?.title ?? id;
const lines: string[] = [w.head];
for (const change of api.getChanges()) {
if (change.state !== 'modified' || !change.cells) {
lines.push(
[
change.key,
w[change.state as 'added' | 'modified' | 'removed'] ?? change.state,
'',
'',
change.row.name,
]
.map(quote)
.join(','),
);
continue;
}
for (const cell of change.cells) {
lines.push(
[change.key, w.modified, title(cell.columnId), cell.oldValue, cell.newValue]
.map(quote)
.join(','),
);
}
}
return lines.join('\n');
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
log('Edit a few cells, then press "Download CSV".');
return api.on('changesCountChanged', ({ count }) => {
const body = (): string => {
const out = changesToCsv(api).split('\n').slice(1);
return out.length ? '\n' + out.join('\n') : '';
};
log(`${count} changed ${count === 1 ? 'row' : 'rows'}${body()}`);
});
}
export const actions = {
add: (api: GridApi<Row>) => {
nextId += 1;
api.addRows([{ id: nextId, name: 'New hire', department: 'Dev', salary: 35000 }], 0);
},
removeSelected: (api: GridApi<Row>) => api.removeRows(api.getSelectedKeys()),
// Put a BOM (\uFEFF) at the start of the file so Excel reads the encoding correctly.
download: (api: GridApi<Row>) => {
if (!api.getChanges().length) return say('Nothing changed, so there is nothing to download.');
const link = document.createElement('a');
link.href = URL.createObjectURL(new Blob(['\uFEFF', changesToCsv(api)], { type: 'text/csv' }));
link.download = WORDS.file;
link.click();
URL.revokeObjectURL(link.href);
say('Downloaded changes.csv.');
},
discard: (api: GridApi<Row>) => api.rollbackChanges(),
};