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

5만 줄을 나눠서 내보내기: 진행률과 취소Export 50,000 rows in chunks with progress and cancel

큰 데이터를 5,000줄씩 나눠 만들면서 진행률을 보여 주고, 도중에 취소해요. 그동안 화면은 멈추지 않아요.Build a large CSV in 5,000-row chunks with progress and a cancel button while the page stays responsive.

심화Advanced
직접 써 보기Live preview5만 줄을 나눠서 내보내기: 진행률과 취소Export 50,000 rows in chunks with progress and cancel

코드Code

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

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

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

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

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

index.html
<div id="app">
  <div class="toolbar">
    <select aria-label="속도" id="speed">
      <option value="slow" selected>천천히 (취소 시험용)</option>
      <option value="fast">그대로</option>
    </select>
    <button type="button" id="start">내보내기 시작</button>
    <button type="button" id="cancel">취소</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('speed').addEventListener('change', (event) => actions.speed(api, event.target.value));
document.getElementById('start').addEventListener('click', () => actions.start(api));
document.getElementById('cancel').addEventListener('click', () => actions.cancel(api));
example.js
import { exportCsvChunks } from '@maxgrid/export';
const rows = Array.from({ length: 50_000 }, (_, i) => ({
  id: i + 1,
  sku: `SKU-${String(i + 1).padStart(6, '0')}`,
  qty: (i * 7) % 500,
  price: 1000 + ((i * 13) % 9000),
}));
// 5만 줄을 5,000줄씩 나눠서 만들면서 중간마다 브라우저에 차례를 넘겨요. 화면이 멈추지 않고 진행률도 보여 줄 수 있어요.
export const options = {
  columns: [
    { id: 'sku', title: '품번', width: 140 },
    { id: 'qty', title: '재고', kind: 'number', width: 90, align: 'end' },
    { id: 'price', title: '단가(원)', kind: 'number', width: 110, align: 'end' },
  ],
  rows,
  rowKey: 'id',
};
let say = () => { };
let running = null;
let slow = true;
export function setup(_api, log) {
  say = log;
  return () => running?.abort(); // 그리드가 사라진 뒤에는 아무것도 돌고 있지 않게 해요.
}
function save(parts, file) {
  const url = URL.createObjectURL(new Blob(parts, { type: 'text/csv;charset=utf-8' }));
  const link = document.createElement('a');
  link.href = url;
  link.download = file;
  link.click();
  setTimeout(() => URL.revokeObjectURL(url), 1000);
}
export const actions = {
  // 요즘 컴퓨터에서는 5만 줄도 금방 끝나서, 취소를 눌러 볼 수 있게 조각마다 잠깐 쉬는 모드를 넣었어요.
  speed: (_api, value) => void (slow = value !== 'fast'),
  start: async (api) => {
    if (running)
      return say({ ko: '이미 만들고 있어요.', en: 'Already building.' });
    const ctrl = (running = new AbortController());
    const parts = [];
    const total = api.getRowCount();
    let done = 0;
    try {
      for await (const chunk of exportCsvChunks(api, { chunkSize: 5_000, signal: ctrl.signal })) {
        parts.push(chunk);
        if (slow)
          await new Promise((resolve) => setTimeout(resolve, 200));
        const next = Math.min(total, done + 5_000);
        if (next === done)
          continue; // 마지막에 오는 빈 조각은 같은 100% 줄을 또 찍지 않게 건너뛰어요.
        done = next;
        say({
          ko: `${Math.round((done / total) * 100)}% (${done.toLocaleString('ko-KR')}줄)`,
          en: `${Math.round((done / total) * 100)}% (${done.toLocaleString('en-US')} rows)`,
        });
      }
      save(parts, '재고-5만줄.csv');
      say({ ko: '다 만들었어요.', en: 'Done.' });
    }
    catch (error) {
      say({
        ko: error instanceof Error && error.name === 'AbortError'
          ? '취소했어요.'
          : `실패했어요: ${String(error)}`,
        en: error instanceof Error && error.name === 'AbortError'
          ? 'Cancelled.'
          : `Failed: ${String(error)}`,
      });
    }
    finally {
      running = null;
    }
  },
  cancel: () => {
    if (!running)
      return say({ ko: '만드는 중이 아니에요.', en: 'Nothing is being built.' });
    running.abort();
  },
};

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

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

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

index.html
<div id="app">
  <div class="toolbar">
    <select aria-label="Speed" id="speed">
      <option value="slow" selected>Slow (to try cancel)</option>
      <option value="fast">Normal</option>
    </select>
    <button type="button" id="start">Start export</button>
    <button type="button" id="cancel">Cancel</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('speed').addEventListener('change', (event) => actions.speed(api, event.target.value));
document.getElementById('start').addEventListener('click', () => actions.start(api));
document.getElementById('cancel').addEventListener('click', () => actions.cancel(api));
example.js
import { exportCsvChunks } from '@maxgrid/export';
const rows = Array.from({ length: 50_000 }, (_, i) => ({
  id: i + 1,
  sku: `SKU-${String(i + 1).padStart(6, '0')}`,
  qty: (i * 7) % 500,
  price: 1000 + ((i * 13) % 9000),
}));
// Build 50,000 rows in chunks of 5,000 and yield to the browser between chunks. The page does not freeze and can show progress.
export const options = {
  columns: [
    { id: 'sku', title: 'SKU', width: 140 },
    { id: 'qty', title: 'Stock', kind: 'number', width: 90, align: 'end' },
    { id: 'price', title: 'Price ($)', kind: 'number', width: 110, align: 'end' },
  ],
  rows,
  rowKey: 'id',
};
let say = () => { };
let running = null;
let slow = true;
export function setup(_api, log) {
  say = log;
  return () => running?.abort(); // Make sure nothing keeps running after the grid is gone.
}
function save(parts, file) {
  const url = URL.createObjectURL(new Blob(parts, { type: 'text/csv;charset=utf-8' }));
  const link = document.createElement('a');
  link.href = url;
  link.download = file;
  link.click();
  setTimeout(() => URL.revokeObjectURL(url), 1000);
}
export const actions = {
  // Modern machines finish 50,000 rows quickly, so a slow mode pauses between chunks to let you try Cancel.
  speed: (_api, value) => void (slow = value !== 'fast'),
  start: async (api) => {
    if (running)
      return say('Already building.');
    const ctrl = (running = new AbortController());
    const parts = [];
    const total = api.getRowCount();
    let done = 0;
    try {
      for await (const chunk of exportCsvChunks(api, { chunkSize: 5_000, signal: ctrl.signal })) {
        parts.push(chunk);
        if (slow)
          await new Promise((resolve) => setTimeout(resolve, 200));
        const next = Math.min(total, done + 5_000);
        if (next === done)
          continue; // Skip the empty last chunk so the 100% line is not logged twice.
        done = next;
        say(`${Math.round((done / total) * 100)}% (${done.toLocaleString('en-US')} rows)`);
      }
      save(parts, 'stock-50k-rows.csv');
      say('Done.');
    }
    catch (error) {
      say(error instanceof Error && error.name === 'AbortError'
        ? 'Cancelled.'
        : `Failed: ${String(error)}`);
    }
    finally {
      running = null;
    }
  },
  cancel: () => {
    if (!running)
      return say('Nothing is being built.');
    running.abort();
  },
};