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.
코드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">
<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>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));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();
},
}; 이 HTML은 추가 번들(위 script 태그)도 함께 불러오고 전역 변수로 써요. 별도 설치는 필요 없어요.
<!doctype html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>5만 줄을 나눠서 내보내기: 진행률과 취소</title>
</head>
<body>
<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>
<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 { exportCsvChunks } = MaxGridExport;
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줄씩 나눠서 만들면서 중간마다 브라우저에 차례를 넘겨요. 화면이 멈추지 않고 진행률도 보여 줄 수 있어요.
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;
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);
}
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();
},
};
options.ariaLabel = "5만 줄을 나눠서 내보내기: 진행률과 취소";
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('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));
</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">
<select
aria-label="속도"
disabled={!api}
onChange={(event) => api && actions.speed(api, event.target.value)}
>
<option value="slow">천천히 (취소 시험용)</option>
<option value="fast">그대로</option>
</select>
<button
type="button"
disabled={!api}
onClick={() => api && actions.start(api)}
>내보내기 시작</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.cancel(api)}
>취소</button>
</div>
<Grid style={{ height: 300 }} ref={gridRef} options={options} />
</>
);
}import { exportCsvChunks } from '@maxgrid/export';
import type { GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
sku: string;
qty: number;
price: number;
}
const rows: Row[] = 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: GridOptions<Row> = {
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: (message: LogText) => void = () => {};
let running: AbortController | null = null;
let slow = true;
export function setup(_api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
return () => running?.abort(); // 그리드가 사라진 뒤에는 아무것도 돌고 있지 않게 해요.
}
function save(parts: string[], file: string): void {
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: GridApi<Row>, value?: string) => void (slow = value !== 'fast'),
start: async (api: GridApi<Row>) => {
if (running) return say({ ko: '이미 만들고 있어요.', en: 'Already building.' });
const ctrl = (running = new AbortController());
const parts: string[] = [];
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();
},
}; 이 예제는 추가 패키지가 필요해요. 내 컴퓨터에서 돌리려면 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">
<select
aria-label="속도"
:disabled="!api"
@change="api && actions.speed(api, ($event.target as HTMLSelectElement).value)"
>
<option value="slow" selected>천천히 (취소 시험용)</option>
<option value="fast">그대로</option>
</select>
<button type="button" :disabled="!api" @click="api && actions.start(api)">내보내기 시작</button>
<button type="button" :disabled="!api" @click="api && actions.cancel(api)">취소</button>
</div>
<Grid style="height: 300px" :options="options" @ready="onReady" />
</template>import { exportCsvChunks } from '@maxgrid/export';
import type { GridApi, GridOptions } from '@maxgrid/vue';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
sku: string;
qty: number;
price: number;
}
const rows: Row[] = 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: GridOptions<Row> = {
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: (message: LogText) => void = () => {};
let running: AbortController | null = null;
let slow = true;
export function setup(_api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
return () => running?.abort(); // 그리드가 사라진 뒤에는 아무것도 돌고 있지 않게 해요.
}
function save(parts: string[], file: string): void {
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: GridApi<Row>, value?: string) => void (slow = value !== 'fast'),
start: async (api: GridApi<Row>) => {
if (running) return say({ ko: '이미 만들고 있어요.', en: 'Already building.' });
const ctrl = (running = new AbortController());
const parts: string[] = [];
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();
},
}; 이 예제는 추가 패키지가 필요해요. 내 컴퓨터에서 돌리려면 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">
<select
aria-label="속도"
[disabled]="!api"
(change)="api && actions.speed(api, $any($event.target).value)"
>
<option value="slow" selected>천천히 (취소 시험용)</option>
<option value="fast">그대로</option>
</select>
<button
type="button"
[disabled]="!api"
(click)="api && actions.start(api)"
>내보내기 시작</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.cancel(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 { exportCsvChunks } from '@maxgrid/export';
import type { GridApi, GridOptions } from '@maxgrid/angular';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
sku: string;
qty: number;
price: number;
}
const rows: Row[] = 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: GridOptions<Row> = {
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: (message: LogText) => void = () => {};
let running: AbortController | null = null;
let slow = true;
export function setup(_api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
return () => running?.abort(); // 그리드가 사라진 뒤에는 아무것도 돌고 있지 않게 해요.
}
function save(parts: string[], file: string): void {
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: GridApi<Row>, value?: string) => void (slow = value !== 'fast'),
start: async (api: GridApi<Row>) => {
if (running) return say({ ko: '이미 만들고 있어요.', en: 'Already building.' });
const ctrl = (running = new AbortController());
const parts: string[] = [];
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();
},
}; 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">
<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>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));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();
},
};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>Export 50,000 rows in chunks with progress and cancel</title>
</head>
<body>
<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>
<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 { exportCsvChunks } = MaxGridExport;
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.
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;
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);
}
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();
},
};
options.ariaLabel = "Export 50,000 rows in chunks with progress and cancel";
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('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));
</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">
<select
aria-label="Speed"
disabled={!api}
onChange={(event) => api && actions.speed(api, event.target.value)}
>
<option value="slow">Slow (to try cancel)</option>
<option value="fast">Normal</option>
</select>
<button
type="button"
disabled={!api}
onClick={() => api && actions.start(api)}
>Start export</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.cancel(api)}
>Cancel</button>
</div>
<Grid style={{ height: 300 }} ref={gridRef} options={options} />
</>
);
}import { exportCsvChunks } from '@maxgrid/export';
import type { GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string;
export interface Row {
id: number;
sku: string;
qty: number;
price: number;
}
const rows: Row[] = 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: GridOptions<Row> = {
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: (message: LogText) => void = () => {};
let running: AbortController | null = null;
let slow = true;
export function setup(_api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
return () => running?.abort(); // Make sure nothing keeps running after the grid is gone.
}
function save(parts: string[], file: string): void {
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: GridApi<Row>, value?: string) => void (slow = value !== 'fast'),
start: async (api: GridApi<Row>) => {
if (running) return say('Already building.');
const ctrl = (running = new AbortController());
const parts: string[] = [];
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();
},
}; 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">
<select
aria-label="Speed"
:disabled="!api"
@change="api && actions.speed(api, ($event.target as HTMLSelectElement).value)"
>
<option value="slow" selected>Slow (to try cancel)</option>
<option value="fast">Normal</option>
</select>
<button type="button" :disabled="!api" @click="api && actions.start(api)">Start export</button>
<button type="button" :disabled="!api" @click="api && actions.cancel(api)">Cancel</button>
</div>
<Grid style="height: 300px" :options="options" @ready="onReady" />
</template>import { exportCsvChunks } from '@maxgrid/export';
import type { GridApi, GridOptions } from '@maxgrid/vue';
export type LogText = string;
export interface Row {
id: number;
sku: string;
qty: number;
price: number;
}
const rows: Row[] = 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: GridOptions<Row> = {
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: (message: LogText) => void = () => {};
let running: AbortController | null = null;
let slow = true;
export function setup(_api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
return () => running?.abort(); // Make sure nothing keeps running after the grid is gone.
}
function save(parts: string[], file: string): void {
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: GridApi<Row>, value?: string) => void (slow = value !== 'fast'),
start: async (api: GridApi<Row>) => {
if (running) return say('Already building.');
const ctrl = (running = new AbortController());
const parts: string[] = [];
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();
},
}; 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">
<select
aria-label="Speed"
[disabled]="!api"
(change)="api && actions.speed(api, $any($event.target).value)"
>
<option value="slow" selected>Slow (to try cancel)</option>
<option value="fast">Normal</option>
</select>
<button
type="button"
[disabled]="!api"
(click)="api && actions.start(api)"
>Start export</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.cancel(api)"
>Cancel</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 { exportCsvChunks } from '@maxgrid/export';
import type { GridApi, GridOptions } from '@maxgrid/angular';
export type LogText = string;
export interface Row {
id: number;
sku: string;
qty: number;
price: number;
}
const rows: Row[] = 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: GridOptions<Row> = {
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: (message: LogText) => void = () => {};
let running: AbortController | null = null;
let slow = true;
export function setup(_api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
return () => running?.abort(); // Make sure nothing keeps running after the grid is gone.
}
function save(parts: string[], file: string): void {
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: GridApi<Row>, value?: string) => void (slow = value !== 'fast'),
start: async (api: GridApi<Row>) => {
if (running) return say('Already building.');
const ctrl = (running = new AbortController());
const parts: string[] = [];
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();
},
};