그리드에 내보내기 기능 붙이기Attach export to the grid
그리드에 내보내기 기능을 붙이면 CSV·엑셀·PDF 파일을 만들 수 있어요. 정렬한 결과가 그대로 파일에 담겨요.One line of code adds export to the grid so you can make CSV, Excel and PDF files. A sorted order carries into the file.
코드Code
탭을 골라 코드를 복사하세요. 위 화면은 이 코드를 그대로 실행한 결과예요.Pick a tab and copy the code. The preview above runs exactly this code.
이 화면은 새 모양 옵션을 켠 모양이에요: density: 'spacious', iconStyle: 'soft', motion: true (코드에 없으면 기본 모양으로 보여요)This preview has the new-look options on: density: 'spacious', iconStyle: 'soft', motion: true (without them in your code you get the default look)
이 예제는 추가 패키지가 필요해요. 내 컴퓨터에서 돌리려면 npm i maxgrid @maxgrid/export로 설치하세요.
버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
<div id="app">
<div class="toolbar">
<button type="button" id="sortByPrice">단가 높은 순 정렬</button>
<button type="button" id="csv">CSV 앞 두 줄 보기</button>
<button type="button" id="xlsx">엑셀 파일 크기 보기</button>
<button type="button" id="pdf">PDF 파일 크기 보기</button>
</div>
<div id="grid" style="height: 330px"></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('sortByPrice').addEventListener('click', () => actions.sortByPrice(api));
document.getElementById('csv').addEventListener('click', () => actions.csv(api));
document.getElementById('xlsx').addEventListener('click', () => actions.xlsx(api));
document.getElementById('pdf').addEventListener('click', () => actions.pdf(api));import { withExport } from '@maxgrid/export';
const customers = ['한빛푸드', '소나무철물', '파란마켓', '단풍상회', '바다유통', '새벽식자재'];
const regions = ['서울', '부산', '대전', '광주'];
const rows = Array.from({ length: 12 }, (_, i) => ({
id: i + 1,
orderNo: `SO-${3001 + i}`,
customer: customers[i % customers.length],
region: regions[i % regions.length],
qty: 3 + ((i * 7) % 28),
price: 4200 + ((i * 1900) % 21000),
orderedAt: new Date(2026, 9, 1 + i * 2),
}));
// withExport(api)는 그리드 api에 내보내기 메서드를 붙여요. 붙인 뒤에는 api.exportCsv(), api.downloadXlsx() 처럼
// 그리드 자신을 원본으로 써서 정렬·필터·선택을 그대로 반영해요. 셀 우클릭 메뉴에도 "내보내기"가 생겨요.
export const options = {
columns: [
{ id: 'orderNo', title: '주문번호', width: 100 },
{ id: 'customer', title: '거래처', width: 110 },
{ id: 'region', title: '지역', width: 70 },
{ id: 'qty', title: '수량', kind: 'number', width: 70, align: 'end' },
{
id: 'price',
title: '단가(원)',
kind: 'number',
width: 100,
align: 'end',
formatValue: (v) => Number(v).toLocaleString('ko-KR'),
},
{ id: 'orderedAt', title: '주문일', kind: 'date', width: 110 },
],
rows,
rowKey: 'id',
};
let say = () => { };
let ex;
export function setup(api, log) {
say = log;
ex = withExport(api);
const ready = ['downloadCsv', 'downloadXlsx', 'downloadPdf'].every((name) => name in api);
log({
ko: ready
? '내보내기 기능을 붙였어요. CSV·엑셀·PDF 파일을 만들 수 있어요.'
: '내보내기 기능을 붙이지 못했어요.',
en: ready
? 'Export is attached. You can make CSV, Excel and PDF files.'
: 'Could not attach export.',
});
}
export const actions = {
sortByPrice: (api) => {
api.setSortModel([{ columnId: 'price', direction: 'desc' }]);
say({
ko: '단가 높은 순으로 정렬했어요. 이제 파일을 만들면 이 순서로 담겨요.',
en: 'Sorted by unit price, highest first. Files made now keep this order.',
});
},
csv: () => {
const lines = (ex?.exportCsv({ bom: false, newline: '\n' }) ?? '').split('\n').slice(0, 2);
// 기록은 위가 최신이라 거꾸로 적어야 위에서 아래로 읽혀요.
for (const line of [...lines].reverse())
say(line);
say({ ko: 'CSV 앞의 두 줄이에요.', en: 'The first two lines of the CSV.' });
},
xlsx: () => say({
ko: `엑셀 파일은 ${ex?.exportXlsx().length.toLocaleString('ko-KR')}바이트예요.`,
en: `The Excel file is ${ex?.exportXlsx().length.toLocaleString('en-US')} bytes.`,
}),
pdf: async () => {
const bytes = await ex?.exportPdf({ font: false, onWarning: () => undefined });
say({
ko: `PDF 파일은 ${bytes?.length.toLocaleString('ko-KR')}바이트예요. (한글 폰트를 넣지 않은 시험이라 한글은 ?로 나와요.)`,
en: `The PDF file is ${bytes?.length.toLocaleString('en-US')} bytes. (This test has no Korean font, so Korean text shows as ?.)`,
});
},
}; 이 HTML은 추가 번들(위 script 태그)도 함께 불러오고 전역 변수로 써요. 별도 설치는 필요 없어요.
<!doctype html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>그리드에 내보내기 기능 붙이기</title>
</head>
<body>
<div class="toolbar">
<button type="button" id="sortByPrice">단가 높은 순 정렬</button>
<button type="button" id="csv">CSV 앞 두 줄 보기</button>
<button type="button" id="xlsx">엑셀 파일 크기 보기</button>
<button type="button" id="pdf">PDF 파일 크기 보기</button>
</div>
<div id="grid" style="height: 330px"></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 { withExport } = MaxGridExport;
const customers = ['한빛푸드', '소나무철물', '파란마켓', '단풍상회', '바다유통', '새벽식자재'];
const regions = ['서울', '부산', '대전', '광주'];
const rows = Array.from({ length: 12 }, (_, i) => ({
id: i + 1,
orderNo: `SO-${3001 + i}`,
customer: customers[i % customers.length],
region: regions[i % regions.length],
qty: 3 + ((i * 7) % 28),
price: 4200 + ((i * 1900) % 21000),
orderedAt: new Date(2026, 9, 1 + i * 2),
}));
// withExport(api)는 그리드 api에 내보내기 메서드를 붙여요. 붙인 뒤에는 api.exportCsv(), api.downloadXlsx() 처럼
// 그리드 자신을 원본으로 써서 정렬·필터·선택을 그대로 반영해요. 셀 우클릭 메뉴에도 "내보내기"가 생겨요.
const options = {
columns: [
{ id: 'orderNo', title: '주문번호', width: 100 },
{ id: 'customer', title: '거래처', width: 110 },
{ id: 'region', title: '지역', width: 70 },
{ id: 'qty', title: '수량', kind: 'number', width: 70, align: 'end' },
{
id: 'price',
title: '단가(원)',
kind: 'number',
width: 100,
align: 'end',
formatValue: (v) => Number(v).toLocaleString('ko-KR'),
},
{ id: 'orderedAt', title: '주문일', kind: 'date', width: 110 },
],
rows,
rowKey: 'id',
};
let say = () => { };
let ex;
function setup(api, log) {
say = log;
ex = withExport(api);
const ready = ['downloadCsv', 'downloadXlsx', 'downloadPdf'].every((name) => name in api);
log({
ko: ready
? '내보내기 기능을 붙였어요. CSV·엑셀·PDF 파일을 만들 수 있어요.'
: '내보내기 기능을 붙이지 못했어요.',
en: ready
? 'Export is attached. You can make CSV, Excel and PDF files.'
: 'Could not attach export.',
});
}
const actions = {
sortByPrice: (api) => {
api.setSortModel([{ columnId: 'price', direction: 'desc' }]);
say({
ko: '단가 높은 순으로 정렬했어요. 이제 파일을 만들면 이 순서로 담겨요.',
en: 'Sorted by unit price, highest first. Files made now keep this order.',
});
},
csv: () => {
const lines = (ex?.exportCsv({ bom: false, newline: '\n' }) ?? '').split('\n').slice(0, 2);
// 기록은 위가 최신이라 거꾸로 적어야 위에서 아래로 읽혀요.
for (const line of [...lines].reverse())
say(line);
say({ ko: 'CSV 앞의 두 줄이에요.', en: 'The first two lines of the CSV.' });
},
xlsx: () => say({
ko: `엑셀 파일은 ${ex?.exportXlsx().length.toLocaleString('ko-KR')}바이트예요.`,
en: `The Excel file is ${ex?.exportXlsx().length.toLocaleString('en-US')} bytes.`,
}),
pdf: async () => {
const bytes = await ex?.exportPdf({ font: false, onWarning: () => undefined });
say({
ko: `PDF 파일은 ${bytes?.length.toLocaleString('ko-KR')}바이트예요. (한글 폰트를 넣지 않은 시험이라 한글은 ?로 나와요.)`,
en: `The PDF file is ${bytes?.length.toLocaleString('en-US')} bytes. (This test has no Korean font, so Korean text shows as ?.)`,
});
},
};
options.ariaLabel = "그리드에 내보내기 기능 붙이기";
const api = MaxGrid.createGrid(document.getElementById('grid'), options);
setup(api, (message) => {
const item = document.createElement('li');
item.textContent =
typeof message === 'string' ? message : navigator.language.startsWith('ko') ? message.ko : message.en;
document.getElementById('log').prepend(item);
});
document.getElementById('sortByPrice').addEventListener('click', () => actions.sortByPrice(api));
document.getElementById('csv').addEventListener('click', () => actions.csv(api));
document.getElementById('xlsx').addEventListener('click', () => actions.xlsx(api));
document.getElementById('pdf').addEventListener('click', () => actions.pdf(api));
</script>
</body>
</html> 이 예제는 추가 패키지가 필요해요. 내 컴퓨터에서 돌리려면 npm i @maxgrid/react @maxgrid/export로 설치하세요.
버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
import { useEffect } from 'react';
import { Grid, useGridApi } from '@maxgrid/react';
import { actions, options, setup, type Row } from './example';
export function ExampleGrid() {
const [api, gridRef] = useGridApi<Row>();
useEffect(() => (api ? setup(api, console.log) : undefined), [api]);
return (
<>
<div className="toolbar">
<button
type="button"
disabled={!api}
onClick={() => api && actions.sortByPrice(api)}
>단가 높은 순 정렬</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.csv(api)}
>CSV 앞 두 줄 보기</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.xlsx(api)}
>엑셀 파일 크기 보기</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.pdf(api)}
>PDF 파일 크기 보기</button>
</div>
<Grid style={{ height: 330 }} ref={gridRef} options={options} />
</>
);
}import { withExport, type ExportableGridApi } from '@maxgrid/export';
import type { GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
orderNo: string;
customer: string;
region: string;
qty: number;
price: number;
orderedAt: Date;
}
const customers = ['한빛푸드', '소나무철물', '파란마켓', '단풍상회', '바다유통', '새벽식자재'];
const regions = ['서울', '부산', '대전', '광주'];
const rows: Row[] = Array.from({ length: 12 }, (_, i) => ({
id: i + 1,
orderNo: `SO-${3001 + i}`,
customer: customers[i % customers.length] as string,
region: regions[i % regions.length] as string,
qty: 3 + ((i * 7) % 28),
price: 4200 + ((i * 1900) % 21000),
orderedAt: new Date(2026, 9, 1 + i * 2),
}));
// withExport(api)는 그리드 api에 내보내기 메서드를 붙여요. 붙인 뒤에는 api.exportCsv(), api.downloadXlsx() 처럼
// 그리드 자신을 원본으로 써서 정렬·필터·선택을 그대로 반영해요. 셀 우클릭 메뉴에도 "내보내기"가 생겨요.
export const options: GridOptions<Row> = {
columns: [
{ id: 'orderNo', title: '주문번호', width: 100 },
{ id: 'customer', title: '거래처', width: 110 },
{ id: 'region', title: '지역', width: 70 },
{ id: 'qty', title: '수량', kind: 'number', width: 70, align: 'end' },
{
id: 'price',
title: '단가(원)',
kind: 'number',
width: 100,
align: 'end',
formatValue: (v) => Number(v).toLocaleString('ko-KR'),
},
{ id: 'orderedAt', title: '주문일', kind: 'date', width: 110 },
],
rows,
rowKey: 'id',
};
let say: (message: LogText) => void = () => {};
let ex: ExportableGridApi<Row> | undefined;
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
ex = withExport(api);
const ready = ['downloadCsv', 'downloadXlsx', 'downloadPdf'].every((name) => name in api);
log({
ko: ready
? '내보내기 기능을 붙였어요. CSV·엑셀·PDF 파일을 만들 수 있어요.'
: '내보내기 기능을 붙이지 못했어요.',
en: ready
? 'Export is attached. You can make CSV, Excel and PDF files.'
: 'Could not attach export.',
});
}
export const actions = {
sortByPrice: (api: GridApi<Row>) => {
api.setSortModel([{ columnId: 'price', direction: 'desc' }]);
say({
ko: '단가 높은 순으로 정렬했어요. 이제 파일을 만들면 이 순서로 담겨요.',
en: 'Sorted by unit price, highest first. Files made now keep this order.',
});
},
csv: () => {
const lines = (ex?.exportCsv({ bom: false, newline: '\n' }) ?? '').split('\n').slice(0, 2);
// 기록은 위가 최신이라 거꾸로 적어야 위에서 아래로 읽혀요.
for (const line of [...lines].reverse()) say(line);
say({ ko: 'CSV 앞의 두 줄이에요.', en: 'The first two lines of the CSV.' });
},
xlsx: () =>
say({
ko: `엑셀 파일은 ${ex?.exportXlsx().length.toLocaleString('ko-KR')}바이트예요.`,
en: `The Excel file is ${ex?.exportXlsx().length.toLocaleString('en-US')} bytes.`,
}),
pdf: async () => {
const bytes = await ex?.exportPdf({ font: false, onWarning: () => undefined });
say({
ko: `PDF 파일은 ${bytes?.length.toLocaleString('ko-KR')}바이트예요. (한글 폰트를 넣지 않은 시험이라 한글은 ?로 나와요.)`,
en: `The PDF file is ${bytes?.length.toLocaleString('en-US')} bytes. (This test has no Korean font, so Korean text shows as ?.)`,
});
},
}; 이 예제는 추가 패키지가 필요해요. 내 컴퓨터에서 돌리려면 npm i @maxgrid/vue @maxgrid/export로 설치하세요.
버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
<script setup lang="ts">
import { onBeforeUnmount, shallowRef } from 'vue';
import { Grid, type GridApi } from '@maxgrid/vue';
import { actions, options, setup, type Row } from './example';
const api = shallowRef<GridApi<Row> | null>(null);
let stop: (() => void) | undefined;
function onReady(event: { api: GridApi<Row> }) {
api.value = event.api;
stop = setup(event.api, console.log);
}
onBeforeUnmount(() => stop?.());
</script>
<template>
<div class="toolbar">
<button
type="button"
:disabled="!api"
@click="api && actions.sortByPrice(api)"
>단가 높은 순 정렬</button>
<button type="button" :disabled="!api" @click="api && actions.csv(api)">CSV 앞 두 줄 보기</button>
<button type="button" :disabled="!api" @click="api && actions.xlsx(api)">엑셀 파일 크기 보기</button>
<button type="button" :disabled="!api" @click="api && actions.pdf(api)">PDF 파일 크기 보기</button>
</div>
<Grid style="height: 330px" :options="options" @ready="onReady" />
</template>import { withExport, type ExportableGridApi } from '@maxgrid/export';
import type { GridApi, GridOptions } from '@maxgrid/vue';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
orderNo: string;
customer: string;
region: string;
qty: number;
price: number;
orderedAt: Date;
}
const customers = ['한빛푸드', '소나무철물', '파란마켓', '단풍상회', '바다유통', '새벽식자재'];
const regions = ['서울', '부산', '대전', '광주'];
const rows: Row[] = Array.from({ length: 12 }, (_, i) => ({
id: i + 1,
orderNo: `SO-${3001 + i}`,
customer: customers[i % customers.length] as string,
region: regions[i % regions.length] as string,
qty: 3 + ((i * 7) % 28),
price: 4200 + ((i * 1900) % 21000),
orderedAt: new Date(2026, 9, 1 + i * 2),
}));
// withExport(api)는 그리드 api에 내보내기 메서드를 붙여요. 붙인 뒤에는 api.exportCsv(), api.downloadXlsx() 처럼
// 그리드 자신을 원본으로 써서 정렬·필터·선택을 그대로 반영해요. 셀 우클릭 메뉴에도 "내보내기"가 생겨요.
export const options: GridOptions<Row> = {
columns: [
{ id: 'orderNo', title: '주문번호', width: 100 },
{ id: 'customer', title: '거래처', width: 110 },
{ id: 'region', title: '지역', width: 70 },
{ id: 'qty', title: '수량', kind: 'number', width: 70, align: 'end' },
{
id: 'price',
title: '단가(원)',
kind: 'number',
width: 100,
align: 'end',
formatValue: (v) => Number(v).toLocaleString('ko-KR'),
},
{ id: 'orderedAt', title: '주문일', kind: 'date', width: 110 },
],
rows,
rowKey: 'id',
};
let say: (message: LogText) => void = () => {};
let ex: ExportableGridApi<Row> | undefined;
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
ex = withExport(api);
const ready = ['downloadCsv', 'downloadXlsx', 'downloadPdf'].every((name) => name in api);
log({
ko: ready
? '내보내기 기능을 붙였어요. CSV·엑셀·PDF 파일을 만들 수 있어요.'
: '내보내기 기능을 붙이지 못했어요.',
en: ready
? 'Export is attached. You can make CSV, Excel and PDF files.'
: 'Could not attach export.',
});
}
export const actions = {
sortByPrice: (api: GridApi<Row>) => {
api.setSortModel([{ columnId: 'price', direction: 'desc' }]);
say({
ko: '단가 높은 순으로 정렬했어요. 이제 파일을 만들면 이 순서로 담겨요.',
en: 'Sorted by unit price, highest first. Files made now keep this order.',
});
},
csv: () => {
const lines = (ex?.exportCsv({ bom: false, newline: '\n' }) ?? '').split('\n').slice(0, 2);
// 기록은 위가 최신이라 거꾸로 적어야 위에서 아래로 읽혀요.
for (const line of [...lines].reverse()) say(line);
say({ ko: 'CSV 앞의 두 줄이에요.', en: 'The first two lines of the CSV.' });
},
xlsx: () =>
say({
ko: `엑셀 파일은 ${ex?.exportXlsx().length.toLocaleString('ko-KR')}바이트예요.`,
en: `The Excel file is ${ex?.exportXlsx().length.toLocaleString('en-US')} bytes.`,
}),
pdf: async () => {
const bytes = await ex?.exportPdf({ font: false, onWarning: () => undefined });
say({
ko: `PDF 파일은 ${bytes?.length.toLocaleString('ko-KR')}바이트예요. (한글 폰트를 넣지 않은 시험이라 한글은 ?로 나와요.)`,
en: `The PDF file is ${bytes?.length.toLocaleString('en-US')} bytes. (This test has no Korean font, so Korean text shows as ?.)`,
});
},
}; 이 예제는 추가 패키지가 필요해요. 내 컴퓨터에서 돌리려면 npm i @maxgrid/angular @maxgrid/export로 설치하세요.
버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
import { Component, OnDestroy } from '@angular/core';
import { GridComponent, isGridEvent, type GridApi, type GridEventMessage } from '@maxgrid/angular';
import { actions, options, setup, type Row } from './example';
@Component({
selector: 'app-example-grid',
standalone: true,
imports: [GridComponent],
template: `
<div class="toolbar">
<button
type="button"
[disabled]="!api"
(click)="api && actions.sortByPrice(api)"
>단가 높은 순 정렬</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.csv(api)"
>CSV 앞 두 줄 보기</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.xlsx(api)"
>엑셀 파일 크기 보기</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.pdf(api)"
>PDF 파일 크기 보기</button>
</div>
<mx-grid style="height: 330px" [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 { withExport, type ExportableGridApi } from '@maxgrid/export';
import type { GridApi, GridOptions } from '@maxgrid/angular';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
orderNo: string;
customer: string;
region: string;
qty: number;
price: number;
orderedAt: Date;
}
const customers = ['한빛푸드', '소나무철물', '파란마켓', '단풍상회', '바다유통', '새벽식자재'];
const regions = ['서울', '부산', '대전', '광주'];
const rows: Row[] = Array.from({ length: 12 }, (_, i) => ({
id: i + 1,
orderNo: `SO-${3001 + i}`,
customer: customers[i % customers.length] as string,
region: regions[i % regions.length] as string,
qty: 3 + ((i * 7) % 28),
price: 4200 + ((i * 1900) % 21000),
orderedAt: new Date(2026, 9, 1 + i * 2),
}));
// withExport(api)는 그리드 api에 내보내기 메서드를 붙여요. 붙인 뒤에는 api.exportCsv(), api.downloadXlsx() 처럼
// 그리드 자신을 원본으로 써서 정렬·필터·선택을 그대로 반영해요. 셀 우클릭 메뉴에도 "내보내기"가 생겨요.
export const options: GridOptions<Row> = {
columns: [
{ id: 'orderNo', title: '주문번호', width: 100 },
{ id: 'customer', title: '거래처', width: 110 },
{ id: 'region', title: '지역', width: 70 },
{ id: 'qty', title: '수량', kind: 'number', width: 70, align: 'end' },
{
id: 'price',
title: '단가(원)',
kind: 'number',
width: 100,
align: 'end',
formatValue: (v) => Number(v).toLocaleString('ko-KR'),
},
{ id: 'orderedAt', title: '주문일', kind: 'date', width: 110 },
],
rows,
rowKey: 'id',
};
let say: (message: LogText) => void = () => {};
let ex: ExportableGridApi<Row> | undefined;
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
ex = withExport(api);
const ready = ['downloadCsv', 'downloadXlsx', 'downloadPdf'].every((name) => name in api);
log({
ko: ready
? '내보내기 기능을 붙였어요. CSV·엑셀·PDF 파일을 만들 수 있어요.'
: '내보내기 기능을 붙이지 못했어요.',
en: ready
? 'Export is attached. You can make CSV, Excel and PDF files.'
: 'Could not attach export.',
});
}
export const actions = {
sortByPrice: (api: GridApi<Row>) => {
api.setSortModel([{ columnId: 'price', direction: 'desc' }]);
say({
ko: '단가 높은 순으로 정렬했어요. 이제 파일을 만들면 이 순서로 담겨요.',
en: 'Sorted by unit price, highest first. Files made now keep this order.',
});
},
csv: () => {
const lines = (ex?.exportCsv({ bom: false, newline: '\n' }) ?? '').split('\n').slice(0, 2);
// 기록은 위가 최신이라 거꾸로 적어야 위에서 아래로 읽혀요.
for (const line of [...lines].reverse()) say(line);
say({ ko: 'CSV 앞의 두 줄이에요.', en: 'The first two lines of the CSV.' });
},
xlsx: () =>
say({
ko: `엑셀 파일은 ${ex?.exportXlsx().length.toLocaleString('ko-KR')}바이트예요.`,
en: `The Excel file is ${ex?.exportXlsx().length.toLocaleString('en-US')} bytes.`,
}),
pdf: async () => {
const bytes = await ex?.exportPdf({ font: false, onWarning: () => undefined });
say({
ko: `PDF 파일은 ${bytes?.length.toLocaleString('ko-KR')}바이트예요. (한글 폰트를 넣지 않은 시험이라 한글은 ?로 나와요.)`,
en: `The PDF file is ${bytes?.length.toLocaleString('en-US')} bytes. (This test has no Korean font, so Korean text shows as ?.)`,
});
},
}; This example needs an extra package. To run it locally, install with npm i maxgrid @maxgrid/export.
When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
<div id="app">
<div class="toolbar">
<button type="button" id="sortByPrice">Sort by price desc</button>
<button type="button" id="csv">CSV first lines</button>
<button type="button" id="xlsx">Excel file size</button>
<button type="button" id="pdf">PDF file size</button>
</div>
<div id="grid" style="height: 330px"></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('sortByPrice').addEventListener('click', () => actions.sortByPrice(api));
document.getElementById('csv').addEventListener('click', () => actions.csv(api));
document.getElementById('xlsx').addEventListener('click', () => actions.xlsx(api));
document.getElementById('pdf').addEventListener('click', () => actions.pdf(api));import { withExport } from '@maxgrid/export';
const customers = [
'Harbor Foods',
'Pine Hardware',
'Blue Market',
'Maple Trading',
'Ocean Supply',
'Dawn Grocers',
];
const regions = ['Seoul', 'Busan', 'Daejeon', 'Gwangju'];
const rows = Array.from({ length: 12 }, (_, i) => ({
id: i + 1,
orderNo: `SO-${3001 + i}`,
customer: customers[i % customers.length],
region: regions[i % regions.length],
qty: 3 + ((i * 7) % 28),
price: 4200 + ((i * 1900) % 21000),
orderedAt: new Date(2026, 9, 1 + i * 2),
}));
// withExport(api) attaches export methods to the grid api. Once attached, calls such as api.exportCsv() and api.downloadXlsx()
// use the grid itself as the source, so sort, filter and selection are reflected. The cell context menu also gets "Export".
export const options = {
columns: [
{ id: 'orderNo', title: 'Order no.', width: 100 },
{ id: 'customer', title: 'Customer', width: 110 },
{ id: 'region', title: 'Region', width: 80 },
{ id: 'qty', title: 'Qty', kind: 'number', width: 70, align: 'end' },
{
id: 'price',
title: 'Price ($)',
kind: 'number',
width: 100,
align: 'end',
formatValue: (v) => Number(v).toLocaleString('en-US'),
},
{ id: 'orderedAt', title: 'Ordered', kind: 'date', width: 110 },
],
rows,
rowKey: 'id',
};
let say = () => { };
let ex;
export function setup(api, log) {
say = log;
ex = withExport(api);
const ready = ['downloadCsv', 'downloadXlsx', 'downloadPdf'].every((name) => name in api);
log(ready
? 'Export is attached. You can make CSV, Excel and PDF files.'
: 'Could not attach export.');
}
export const actions = {
sortByPrice: (api) => {
api.setSortModel([{ columnId: 'price', direction: 'desc' }]);
say('Sorted by price, highest first. Files made now keep this order.');
},
csv: () => {
const lines = (ex?.exportCsv({ bom: false, newline: '\n' }) ?? '').split('\n').slice(0, 2);
// The log shows the newest line on top, so write in reverse to read top to bottom.
for (const line of [...lines].reverse())
say(line);
say('The first two lines of the CSV.');
},
xlsx: () => say(`The Excel file is ${ex?.exportXlsx().length.toLocaleString('en-US')} bytes.`),
pdf: async () => {
const bytes = await ex?.exportPdf({ font: false, onWarning: () => undefined });
say(`The PDF file is ${bytes?.length.toLocaleString('en-US')} bytes. (This test has no Korean font, so Korean text would show as ?.)`);
},
};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>Attach export to the grid</title>
</head>
<body>
<div class="toolbar">
<button type="button" id="sortByPrice">Sort by price desc</button>
<button type="button" id="csv">CSV first lines</button>
<button type="button" id="xlsx">Excel file size</button>
<button type="button" id="pdf">PDF file size</button>
</div>
<div id="grid" style="height: 330px"></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 { withExport } = MaxGridExport;
const customers = [
'Harbor Foods',
'Pine Hardware',
'Blue Market',
'Maple Trading',
'Ocean Supply',
'Dawn Grocers',
];
const regions = ['Seoul', 'Busan', 'Daejeon', 'Gwangju'];
const rows = Array.from({ length: 12 }, (_, i) => ({
id: i + 1,
orderNo: `SO-${3001 + i}`,
customer: customers[i % customers.length],
region: regions[i % regions.length],
qty: 3 + ((i * 7) % 28),
price: 4200 + ((i * 1900) % 21000),
orderedAt: new Date(2026, 9, 1 + i * 2),
}));
// withExport(api) attaches export methods to the grid api. Once attached, calls such as api.exportCsv() and api.downloadXlsx()
// use the grid itself as the source, so sort, filter and selection are reflected. The cell context menu also gets "Export".
const options = {
columns: [
{ id: 'orderNo', title: 'Order no.', width: 100 },
{ id: 'customer', title: 'Customer', width: 110 },
{ id: 'region', title: 'Region', width: 80 },
{ id: 'qty', title: 'Qty', kind: 'number', width: 70, align: 'end' },
{
id: 'price',
title: 'Price ($)',
kind: 'number',
width: 100,
align: 'end',
formatValue: (v) => Number(v).toLocaleString('en-US'),
},
{ id: 'orderedAt', title: 'Ordered', kind: 'date', width: 110 },
],
rows,
rowKey: 'id',
};
let say = () => { };
let ex;
function setup(api, log) {
say = log;
ex = withExport(api);
const ready = ['downloadCsv', 'downloadXlsx', 'downloadPdf'].every((name) => name in api);
log(ready
? 'Export is attached. You can make CSV, Excel and PDF files.'
: 'Could not attach export.');
}
const actions = {
sortByPrice: (api) => {
api.setSortModel([{ columnId: 'price', direction: 'desc' }]);
say('Sorted by price, highest first. Files made now keep this order.');
},
csv: () => {
const lines = (ex?.exportCsv({ bom: false, newline: '\n' }) ?? '').split('\n').slice(0, 2);
// The log shows the newest line on top, so write in reverse to read top to bottom.
for (const line of [...lines].reverse())
say(line);
say('The first two lines of the CSV.');
},
xlsx: () => say(`The Excel file is ${ex?.exportXlsx().length.toLocaleString('en-US')} bytes.`),
pdf: async () => {
const bytes = await ex?.exportPdf({ font: false, onWarning: () => undefined });
say(`The PDF file is ${bytes?.length.toLocaleString('en-US')} bytes. (This test has no Korean font, so Korean text would show as ?.)`);
},
};
options.ariaLabel = "Attach export to the grid";
const api = MaxGrid.createGrid(document.getElementById('grid'), options);
setup(api, (message) => {
const item = document.createElement('li');
item.textContent =
typeof message === 'string' ? message : navigator.language.startsWith('ko') ? message.ko : message.en;
document.getElementById('log').prepend(item);
});
document.getElementById('sortByPrice').addEventListener('click', () => actions.sortByPrice(api));
document.getElementById('csv').addEventListener('click', () => actions.csv(api));
document.getElementById('xlsx').addEventListener('click', () => actions.xlsx(api));
document.getElementById('pdf').addEventListener('click', () => actions.pdf(api));
</script>
</body>
</html> This example needs an extra package. To run it locally, install with npm i @maxgrid/react @maxgrid/export.
When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
import { useEffect } from 'react';
import { Grid, useGridApi } from '@maxgrid/react';
import { actions, options, setup, type Row } from './example';
export function ExampleGrid() {
const [api, gridRef] = useGridApi<Row>();
useEffect(() => (api ? setup(api, console.log) : undefined), [api]);
return (
<>
<div className="toolbar">
<button
type="button"
disabled={!api}
onClick={() => api && actions.sortByPrice(api)}
>Sort by price desc</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.csv(api)}
>CSV first lines</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.xlsx(api)}
>Excel file size</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.pdf(api)}
>PDF file size</button>
</div>
<Grid style={{ height: 330 }} ref={gridRef} options={options} />
</>
);
}import { withExport, type ExportableGridApi } from '@maxgrid/export';
import type { GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string;
export interface Row {
id: number;
orderNo: string;
customer: string;
region: string;
qty: number;
price: number;
orderedAt: Date;
}
const customers = [
'Harbor Foods',
'Pine Hardware',
'Blue Market',
'Maple Trading',
'Ocean Supply',
'Dawn Grocers',
];
const regions = ['Seoul', 'Busan', 'Daejeon', 'Gwangju'];
const rows: Row[] = Array.from({ length: 12 }, (_, i) => ({
id: i + 1,
orderNo: `SO-${3001 + i}`,
customer: customers[i % customers.length] as string,
region: regions[i % regions.length] as string,
qty: 3 + ((i * 7) % 28),
price: 4200 + ((i * 1900) % 21000),
orderedAt: new Date(2026, 9, 1 + i * 2),
}));
// withExport(api) attaches export methods to the grid api. Once attached, calls such as api.exportCsv() and api.downloadXlsx()
// use the grid itself as the source, so sort, filter and selection are reflected. The cell context menu also gets "Export".
export const options: GridOptions<Row> = {
columns: [
{ id: 'orderNo', title: 'Order no.', width: 100 },
{ id: 'customer', title: 'Customer', width: 110 },
{ id: 'region', title: 'Region', width: 80 },
{ id: 'qty', title: 'Qty', kind: 'number', width: 70, align: 'end' },
{
id: 'price',
title: 'Price ($)',
kind: 'number',
width: 100,
align: 'end',
formatValue: (v) => Number(v).toLocaleString('en-US'),
},
{ id: 'orderedAt', title: 'Ordered', kind: 'date', width: 110 },
],
rows,
rowKey: 'id',
};
let say: (message: LogText) => void = () => {};
let ex: ExportableGridApi<Row> | undefined;
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
ex = withExport(api);
const ready = ['downloadCsv', 'downloadXlsx', 'downloadPdf'].every((name) => name in api);
log(
ready
? 'Export is attached. You can make CSV, Excel and PDF files.'
: 'Could not attach export.',
);
}
export const actions = {
sortByPrice: (api: GridApi<Row>) => {
api.setSortModel([{ columnId: 'price', direction: 'desc' }]);
say('Sorted by price, highest first. Files made now keep this order.');
},
csv: () => {
const lines = (ex?.exportCsv({ bom: false, newline: '\n' }) ?? '').split('\n').slice(0, 2);
// The log shows the newest line on top, so write in reverse to read top to bottom.
for (const line of [...lines].reverse()) say(line);
say('The first two lines of the CSV.');
},
xlsx: () => say(`The Excel file is ${ex?.exportXlsx().length.toLocaleString('en-US')} bytes.`),
pdf: async () => {
const bytes = await ex?.exportPdf({ font: false, onWarning: () => undefined });
say(
`The PDF file is ${bytes?.length.toLocaleString('en-US')} bytes. (This test has no Korean font, so Korean text would show as ?.)`,
);
},
}; This example needs an extra package. To run it locally, install with npm i @maxgrid/vue @maxgrid/export.
When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
<script setup lang="ts">
import { onBeforeUnmount, shallowRef } from 'vue';
import { Grid, type GridApi } from '@maxgrid/vue';
import { actions, options, setup, type Row } from './example';
const api = shallowRef<GridApi<Row> | null>(null);
let stop: (() => void) | undefined;
function onReady(event: { api: GridApi<Row> }) {
api.value = event.api;
stop = setup(event.api, console.log);
}
onBeforeUnmount(() => stop?.());
</script>
<template>
<div class="toolbar">
<button
type="button"
:disabled="!api"
@click="api && actions.sortByPrice(api)"
>Sort by price desc</button>
<button type="button" :disabled="!api" @click="api && actions.csv(api)">CSV first lines</button>
<button type="button" :disabled="!api" @click="api && actions.xlsx(api)">Excel file size</button>
<button type="button" :disabled="!api" @click="api && actions.pdf(api)">PDF file size</button>
</div>
<Grid style="height: 330px" :options="options" @ready="onReady" />
</template>import { withExport, type ExportableGridApi } from '@maxgrid/export';
import type { GridApi, GridOptions } from '@maxgrid/vue';
export type LogText = string;
export interface Row {
id: number;
orderNo: string;
customer: string;
region: string;
qty: number;
price: number;
orderedAt: Date;
}
const customers = [
'Harbor Foods',
'Pine Hardware',
'Blue Market',
'Maple Trading',
'Ocean Supply',
'Dawn Grocers',
];
const regions = ['Seoul', 'Busan', 'Daejeon', 'Gwangju'];
const rows: Row[] = Array.from({ length: 12 }, (_, i) => ({
id: i + 1,
orderNo: `SO-${3001 + i}`,
customer: customers[i % customers.length] as string,
region: regions[i % regions.length] as string,
qty: 3 + ((i * 7) % 28),
price: 4200 + ((i * 1900) % 21000),
orderedAt: new Date(2026, 9, 1 + i * 2),
}));
// withExport(api) attaches export methods to the grid api. Once attached, calls such as api.exportCsv() and api.downloadXlsx()
// use the grid itself as the source, so sort, filter and selection are reflected. The cell context menu also gets "Export".
export const options: GridOptions<Row> = {
columns: [
{ id: 'orderNo', title: 'Order no.', width: 100 },
{ id: 'customer', title: 'Customer', width: 110 },
{ id: 'region', title: 'Region', width: 80 },
{ id: 'qty', title: 'Qty', kind: 'number', width: 70, align: 'end' },
{
id: 'price',
title: 'Price ($)',
kind: 'number',
width: 100,
align: 'end',
formatValue: (v) => Number(v).toLocaleString('en-US'),
},
{ id: 'orderedAt', title: 'Ordered', kind: 'date', width: 110 },
],
rows,
rowKey: 'id',
};
let say: (message: LogText) => void = () => {};
let ex: ExportableGridApi<Row> | undefined;
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
ex = withExport(api);
const ready = ['downloadCsv', 'downloadXlsx', 'downloadPdf'].every((name) => name in api);
log(
ready
? 'Export is attached. You can make CSV, Excel and PDF files.'
: 'Could not attach export.',
);
}
export const actions = {
sortByPrice: (api: GridApi<Row>) => {
api.setSortModel([{ columnId: 'price', direction: 'desc' }]);
say('Sorted by price, highest first. Files made now keep this order.');
},
csv: () => {
const lines = (ex?.exportCsv({ bom: false, newline: '\n' }) ?? '').split('\n').slice(0, 2);
// The log shows the newest line on top, so write in reverse to read top to bottom.
for (const line of [...lines].reverse()) say(line);
say('The first two lines of the CSV.');
},
xlsx: () => say(`The Excel file is ${ex?.exportXlsx().length.toLocaleString('en-US')} bytes.`),
pdf: async () => {
const bytes = await ex?.exportPdf({ font: false, onWarning: () => undefined });
say(
`The PDF file is ${bytes?.length.toLocaleString('en-US')} bytes. (This test has no Korean font, so Korean text would show as ?.)`,
);
},
}; This example needs an extra package. To run it locally, install with npm i @maxgrid/angular @maxgrid/export.
When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
import { Component, OnDestroy } from '@angular/core';
import { GridComponent, isGridEvent, type GridApi, type GridEventMessage } from '@maxgrid/angular';
import { actions, options, setup, type Row } from './example';
@Component({
selector: 'app-example-grid',
standalone: true,
imports: [GridComponent],
template: `
<div class="toolbar">
<button
type="button"
[disabled]="!api"
(click)="api && actions.sortByPrice(api)"
>Sort by price desc</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.csv(api)"
>CSV first lines</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.xlsx(api)"
>Excel file size</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.pdf(api)"
>PDF file size</button>
</div>
<mx-grid style="height: 330px" [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 { withExport, type ExportableGridApi } from '@maxgrid/export';
import type { GridApi, GridOptions } from '@maxgrid/angular';
export type LogText = string;
export interface Row {
id: number;
orderNo: string;
customer: string;
region: string;
qty: number;
price: number;
orderedAt: Date;
}
const customers = [
'Harbor Foods',
'Pine Hardware',
'Blue Market',
'Maple Trading',
'Ocean Supply',
'Dawn Grocers',
];
const regions = ['Seoul', 'Busan', 'Daejeon', 'Gwangju'];
const rows: Row[] = Array.from({ length: 12 }, (_, i) => ({
id: i + 1,
orderNo: `SO-${3001 + i}`,
customer: customers[i % customers.length] as string,
region: regions[i % regions.length] as string,
qty: 3 + ((i * 7) % 28),
price: 4200 + ((i * 1900) % 21000),
orderedAt: new Date(2026, 9, 1 + i * 2),
}));
// withExport(api) attaches export methods to the grid api. Once attached, calls such as api.exportCsv() and api.downloadXlsx()
// use the grid itself as the source, so sort, filter and selection are reflected. The cell context menu also gets "Export".
export const options: GridOptions<Row> = {
columns: [
{ id: 'orderNo', title: 'Order no.', width: 100 },
{ id: 'customer', title: 'Customer', width: 110 },
{ id: 'region', title: 'Region', width: 80 },
{ id: 'qty', title: 'Qty', kind: 'number', width: 70, align: 'end' },
{
id: 'price',
title: 'Price ($)',
kind: 'number',
width: 100,
align: 'end',
formatValue: (v) => Number(v).toLocaleString('en-US'),
},
{ id: 'orderedAt', title: 'Ordered', kind: 'date', width: 110 },
],
rows,
rowKey: 'id',
};
let say: (message: LogText) => void = () => {};
let ex: ExportableGridApi<Row> | undefined;
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
ex = withExport(api);
const ready = ['downloadCsv', 'downloadXlsx', 'downloadPdf'].every((name) => name in api);
log(
ready
? 'Export is attached. You can make CSV, Excel and PDF files.'
: 'Could not attach export.',
);
}
export const actions = {
sortByPrice: (api: GridApi<Row>) => {
api.setSortModel([{ columnId: 'price', direction: 'desc' }]);
say('Sorted by price, highest first. Files made now keep this order.');
},
csv: () => {
const lines = (ex?.exportCsv({ bom: false, newline: '\n' }) ?? '').split('\n').slice(0, 2);
// The log shows the newest line on top, so write in reverse to read top to bottom.
for (const line of [...lines].reverse()) say(line);
say('The first two lines of the CSV.');
},
xlsx: () => say(`The Excel file is ${ex?.exportXlsx().length.toLocaleString('en-US')} bytes.`),
pdf: async () => {
const bytes = await ex?.exportPdf({ font: false, onWarning: () => undefined });
say(
`The PDF file is ${bytes?.length.toLocaleString('en-US')} bytes. (This test has no Korean font, so Korean text would show as ?.)`,
);
},
};