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

바뀐 내용만 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.

활용Intermediate
직접 써 보기Live preview바뀐 내용만 CSV로 내려받기Download only the changes as CSV

코드Code

탭을 골라 코드를 복사하세요. 위 화면은 이 코드를 그대로 실행한 결과예요.Pick a tab and copy the code. The preview above runs exactly this code.

이 화면은 새 모양 옵션을 켠 모양이에요: density: 'spacious', iconStyle: 'soft', motion: true (코드에 없으면 기본 모양으로 보여요)This preview has the new-look options on: density: 'spacious', iconStyle: 'soft', motion: true (without them in your code you get the default look)

빌드 도구(Vite 등)를 쓰는 프로젝트용 모듈 파일이에요. 설치 없이 바로 돌려 보려면 HTML 탭이나 직접 해보기를 쓰세요.

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

index.html
<div id="app">
  <div class="toolbar">
    <button type="button" id="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>
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('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));
example.js
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(),
};

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

When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.

index.html
<div id="app">
  <div class="toolbar">
    <button type="button" id="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>
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('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));
example.js
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(),
};