셀 색·굵게·병합·그림을 담아 내보내기Export with colors, bold, merged cells and pictures
머리글 배경색, 수량이 많은 칸의 빨간 굵은 글씨, 같은 지역을 합친 칸, 재고 표시 그림을 xlsx에 담아요.Put a header background, red bold large quantities and merged region cells into the xlsx.
코드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="styled">
<option value="on" selected>넣기</option>
<option value="off">빼기</option>
</select>
<select aria-label="지역 칸 합치기" id="merged">
<option value="on" selected>합치기</option>
<option value="off">안 합치기</option>
</select>
<select aria-label="그림" id="pictured">
<option value="on" selected>넣기</option>
<option value="off">빼기</option>
</select>
<button type="button" id="download">내려받기</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('styled').addEventListener('change', (event) => actions.styled(api, event.target.value));
document.getElementById('merged').addEventListener('change', (event) => actions.merged(api, event.target.value));
document.getElementById('pictured').addEventListener('change', (event) => actions.pictured(api, event.target.value));
document.getElementById('download').addEventListener('click', () => actions.download(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),
}));
// 머리글 색, 조건에 따른 셀 색·굵게, 같은 지역 셀 합치기(xlsx만), 셀 안 이미지를 담아요.
const sorted = [...rows].sort((a, b) => a.region.localeCompare(b.region, 'ko'));
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: 'level', title: '재고 표시', width: 80, getValue: () => '' },
{
id: 'price',
title: '단가(원)',
kind: 'number',
width: 100,
align: 'end',
formatValue: (v) => Number(v).toLocaleString('ko-KR'),
},
{ id: 'orderedAt', title: '주문일', kind: 'date', width: 110 },
],
rows: sorted,
rowKey: 'id',
};
// 재고 상태 칸: 화면에는 글자 대신 비워 두고, 내보낼 때만 색 동그라미 그림을 넣어요(PNG는 캔버스로 만들어요).
function dot(color) {
const canvas = document.createElement('canvas');
canvas.width = canvas.height = 24;
const g = canvas.getContext('2d');
if (g) {
g.fillStyle = color;
g.beginPath();
g.arc(12, 12, 10, 0, Math.PI * 2);
g.fill();
}
return canvas.toDataURL('image/png');
}
const dots = { many: dot('#dc2626'), few: dot('#16a34a') };
let styled = true;
let merged = true;
let pictured = true;
let say = () => { };
export function setup(api, log) {
say = log;
withExport(api);
}
// 지역이 같은 연속된 줄을 찾아 지역 칸을 위아래로 합쳐요.
function regionMerges(list) {
const out = [];
for (let i = 0; i < list.length;) {
let j = i;
while (j + 1 < list.length && list[j + 1]?.region === list[i]?.region)
j += 1;
if (j > i)
out.push({ row: i, column: 2, rowSpan: j - i + 1 });
i = j + 1;
}
return out;
}
export const actions = {
styled: (_api, v) => void (styled = v !== 'off'),
merged: (_api, v) => void (merged = v !== 'off'),
pictured: (_api, v) => void (pictured = v !== 'off'),
download: async (api) => {
const ex = withExport(api);
const visible = api.getVisibleRows();
await ex.downloadXlsx('주문-서식.xlsx', {
applyFormatValue: false, // 단가가 글자가 아니라 숫자로 들어가요
...(styled
? {
headerStyle: { background: '#1d4ed8', color: '#ffffff', bold: true },
cellStyle: (c) => c.kind === 'data' && c.column.id === 'qty' && Number(c.value) >= 20
? { color: '#b91c1c', bold: true }
: null,
}
: {}),
...(merged ? { merges: regionMerges(visible) } : {}),
...(pictured
? {
cellImage: (c) => c.kind === 'data' && c.column.id === 'level'
? Number(c.row?.qty) >= 20
? dots.many
: dots.few
: null,
}
: {}),
});
say({
ko: `내려받았어요. 서식 ${styled ? '넣음' : '없음'} · 지역 합치기 ${merged ? '켬' : '끔'} · 그림 ${pictured ? '넣음' : '없음'}`,
en: `Downloaded. Styles ${styled ? 'included' : 'none'} · region merge ${merged ? 'on' : 'off'} · picture ${pictured ? 'included' : 'none'}`,
});
},
}; 이 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">
<select aria-label="서식" id="styled">
<option value="on" selected>넣기</option>
<option value="off">빼기</option>
</select>
<select aria-label="지역 칸 합치기" id="merged">
<option value="on" selected>합치기</option>
<option value="off">안 합치기</option>
</select>
<select aria-label="그림" id="pictured">
<option value="on" selected>넣기</option>
<option value="off">빼기</option>
</select>
<button type="button" id="download">내려받기</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),
}));
// 머리글 색, 조건에 따른 셀 색·굵게, 같은 지역 셀 합치기(xlsx만), 셀 안 이미지를 담아요.
const sorted = [...rows].sort((a, b) => a.region.localeCompare(b.region, 'ko'));
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: 'level', title: '재고 표시', width: 80, getValue: () => '' },
{
id: 'price',
title: '단가(원)',
kind: 'number',
width: 100,
align: 'end',
formatValue: (v) => Number(v).toLocaleString('ko-KR'),
},
{ id: 'orderedAt', title: '주문일', kind: 'date', width: 110 },
],
rows: sorted,
rowKey: 'id',
};
// 재고 상태 칸: 화면에는 글자 대신 비워 두고, 내보낼 때만 색 동그라미 그림을 넣어요(PNG는 캔버스로 만들어요).
function dot(color) {
const canvas = document.createElement('canvas');
canvas.width = canvas.height = 24;
const g = canvas.getContext('2d');
if (g) {
g.fillStyle = color;
g.beginPath();
g.arc(12, 12, 10, 0, Math.PI * 2);
g.fill();
}
return canvas.toDataURL('image/png');
}
const dots = { many: dot('#dc2626'), few: dot('#16a34a') };
let styled = true;
let merged = true;
let pictured = true;
let say = () => { };
function setup(api, log) {
say = log;
withExport(api);
}
// 지역이 같은 연속된 줄을 찾아 지역 칸을 위아래로 합쳐요.
function regionMerges(list) {
const out = [];
for (let i = 0; i < list.length;) {
let j = i;
while (j + 1 < list.length && list[j + 1]?.region === list[i]?.region)
j += 1;
if (j > i)
out.push({ row: i, column: 2, rowSpan: j - i + 1 });
i = j + 1;
}
return out;
}
const actions = {
styled: (_api, v) => void (styled = v !== 'off'),
merged: (_api, v) => void (merged = v !== 'off'),
pictured: (_api, v) => void (pictured = v !== 'off'),
download: async (api) => {
const ex = withExport(api);
const visible = api.getVisibleRows();
await ex.downloadXlsx('주문-서식.xlsx', {
applyFormatValue: false, // 단가가 글자가 아니라 숫자로 들어가요
...(styled
? {
headerStyle: { background: '#1d4ed8', color: '#ffffff', bold: true },
cellStyle: (c) => c.kind === 'data' && c.column.id === 'qty' && Number(c.value) >= 20
? { color: '#b91c1c', bold: true }
: null,
}
: {}),
...(merged ? { merges: regionMerges(visible) } : {}),
...(pictured
? {
cellImage: (c) => c.kind === 'data' && c.column.id === 'level'
? Number(c.row?.qty) >= 20
? dots.many
: dots.few
: null,
}
: {}),
});
say({
ko: `내려받았어요. 서식 ${styled ? '넣음' : '없음'} · 지역 합치기 ${merged ? '켬' : '끔'} · 그림 ${pictured ? '넣음' : '없음'}`,
en: `Downloaded. Styles ${styled ? 'included' : 'none'} · region merge ${merged ? 'on' : 'off'} · picture ${pictured ? 'included' : 'none'}`,
});
},
};
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('styled').addEventListener('change', (event) => actions.styled(api, event.target.value));
document.getElementById('merged').addEventListener('change', (event) => actions.merged(api, event.target.value));
document.getElementById('pictured').addEventListener('change', (event) => actions.pictured(api, event.target.value));
document.getElementById('download').addEventListener('click', () => actions.download(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.styled(api, event.target.value)}
>
<option value="on">넣기</option>
<option value="off">빼기</option>
</select>
<select defaultValue="on"
aria-label="지역 칸 합치기"
disabled={!api}
onChange={(event) => api && actions.merged(api, event.target.value)}
>
<option value="on">합치기</option>
<option value="off">안 합치기</option>
</select>
<select defaultValue="on"
aria-label="그림"
disabled={!api}
onChange={(event) => api && actions.pictured(api, event.target.value)}
>
<option value="on">넣기</option>
<option value="off">빼기</option>
</select>
<button
type="button"
disabled={!api}
onClick={() => api && actions.download(api)}
>내려받기</button>
</div>
<Grid style={{ height: 330 }} ref={gridRef} options={options} />
</>
);
}import { withExport, type CellStyleContext } 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),
}));
// 머리글 색, 조건에 따른 셀 색·굵게, 같은 지역 셀 합치기(xlsx만), 셀 안 이미지를 담아요.
const sorted = [...rows].sort((a, b) => a.region.localeCompare(b.region, 'ko'));
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: 'level', title: '재고 표시', width: 80, getValue: () => '' },
{
id: 'price',
title: '단가(원)',
kind: 'number',
width: 100,
align: 'end',
formatValue: (v) => Number(v).toLocaleString('ko-KR'),
},
{ id: 'orderedAt', title: '주문일', kind: 'date', width: 110 },
],
rows: sorted,
rowKey: 'id',
};
// 재고 상태 칸: 화면에는 글자 대신 비워 두고, 내보낼 때만 색 동그라미 그림을 넣어요(PNG는 캔버스로 만들어요).
function dot(color: string): string {
const canvas = document.createElement('canvas');
canvas.width = canvas.height = 24;
const g = canvas.getContext('2d');
if (g) {
g.fillStyle = color;
g.beginPath();
g.arc(12, 12, 10, 0, Math.PI * 2);
g.fill();
}
return canvas.toDataURL('image/png');
}
const dots = { many: dot('#dc2626'), few: dot('#16a34a') };
let styled = true;
let merged = true;
let pictured = true;
let say: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
withExport(api);
}
// 지역이 같은 연속된 줄을 찾아 지역 칸을 위아래로 합쳐요.
function regionMerges(list: readonly Row[]) {
const out: { row: number; column: number; rowSpan: number }[] = [];
for (let i = 0; i < list.length;) {
let j = i;
while (j + 1 < list.length && list[j + 1]?.region === list[i]?.region) j += 1;
if (j > i) out.push({ row: i, column: 2, rowSpan: j - i + 1 });
i = j + 1;
}
return out;
}
export const actions = {
styled: (_api: GridApi<Row>, v?: string) => void (styled = v !== 'off'),
merged: (_api: GridApi<Row>, v?: string) => void (merged = v !== 'off'),
pictured: (_api: GridApi<Row>, v?: string) => void (pictured = v !== 'off'),
download: async (api: GridApi<Row>) => {
const ex = withExport(api);
const visible = api.getVisibleRows();
await ex.downloadXlsx('주문-서식.xlsx', {
applyFormatValue: false, // 단가가 글자가 아니라 숫자로 들어가요
...(styled
? {
headerStyle: { background: '#1d4ed8', color: '#ffffff', bold: true },
cellStyle: (c: CellStyleContext<Row>) =>
c.kind === 'data' && c.column.id === 'qty' && Number(c.value) >= 20
? { color: '#b91c1c', bold: true }
: null,
}
: {}),
...(merged ? { merges: regionMerges(visible) } : {}),
...(pictured
? {
cellImage: (c: CellStyleContext<Row>) =>
c.kind === 'data' && c.column.id === 'level'
? Number(c.row?.qty) >= 20
? dots.many
: dots.few
: null,
}
: {}),
});
say({
ko: `내려받았어요. 서식 ${styled ? '넣음' : '없음'} · 지역 합치기 ${merged ? '켬' : '끔'} · 그림 ${pictured ? '넣음' : '없음'}`,
en: `Downloaded. Styles ${styled ? 'included' : 'none'} · region merge ${merged ? 'on' : 'off'} · picture ${pictured ? 'included' : 'none'}`,
});
},
}; 이 예제는 추가 패키지가 필요해요. 내 컴퓨터에서 돌리려면 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.styled(api, ($event.target as HTMLSelectElement).value)"
>
<option value="on" selected>넣기</option>
<option value="off">빼기</option>
</select>
<select
aria-label="지역 칸 합치기"
:disabled="!api"
@change="api && actions.merged(api, ($event.target as HTMLSelectElement).value)"
>
<option value="on" selected>합치기</option>
<option value="off">안 합치기</option>
</select>
<select
aria-label="그림"
:disabled="!api"
@change="api && actions.pictured(api, ($event.target as HTMLSelectElement).value)"
>
<option value="on" selected>넣기</option>
<option value="off">빼기</option>
</select>
<button
type="button"
:disabled="!api"
@click="api && actions.download(api)"
>내려받기</button>
</div>
<Grid style="height: 330px" :options="options" @ready="onReady" />
</template>import { withExport, type CellStyleContext } 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),
}));
// 머리글 색, 조건에 따른 셀 색·굵게, 같은 지역 셀 합치기(xlsx만), 셀 안 이미지를 담아요.
const sorted = [...rows].sort((a, b) => a.region.localeCompare(b.region, 'ko'));
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: 'level', title: '재고 표시', width: 80, getValue: () => '' },
{
id: 'price',
title: '단가(원)',
kind: 'number',
width: 100,
align: 'end',
formatValue: (v) => Number(v).toLocaleString('ko-KR'),
},
{ id: 'orderedAt', title: '주문일', kind: 'date', width: 110 },
],
rows: sorted,
rowKey: 'id',
};
// 재고 상태 칸: 화면에는 글자 대신 비워 두고, 내보낼 때만 색 동그라미 그림을 넣어요(PNG는 캔버스로 만들어요).
function dot(color: string): string {
const canvas = document.createElement('canvas');
canvas.width = canvas.height = 24;
const g = canvas.getContext('2d');
if (g) {
g.fillStyle = color;
g.beginPath();
g.arc(12, 12, 10, 0, Math.PI * 2);
g.fill();
}
return canvas.toDataURL('image/png');
}
const dots = { many: dot('#dc2626'), few: dot('#16a34a') };
let styled = true;
let merged = true;
let pictured = true;
let say: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
withExport(api);
}
// 지역이 같은 연속된 줄을 찾아 지역 칸을 위아래로 합쳐요.
function regionMerges(list: readonly Row[]) {
const out: { row: number; column: number; rowSpan: number }[] = [];
for (let i = 0; i < list.length;) {
let j = i;
while (j + 1 < list.length && list[j + 1]?.region === list[i]?.region) j += 1;
if (j > i) out.push({ row: i, column: 2, rowSpan: j - i + 1 });
i = j + 1;
}
return out;
}
export const actions = {
styled: (_api: GridApi<Row>, v?: string) => void (styled = v !== 'off'),
merged: (_api: GridApi<Row>, v?: string) => void (merged = v !== 'off'),
pictured: (_api: GridApi<Row>, v?: string) => void (pictured = v !== 'off'),
download: async (api: GridApi<Row>) => {
const ex = withExport(api);
const visible = api.getVisibleRows();
await ex.downloadXlsx('주문-서식.xlsx', {
applyFormatValue: false, // 단가가 글자가 아니라 숫자로 들어가요
...(styled
? {
headerStyle: { background: '#1d4ed8', color: '#ffffff', bold: true },
cellStyle: (c: CellStyleContext<Row>) =>
c.kind === 'data' && c.column.id === 'qty' && Number(c.value) >= 20
? { color: '#b91c1c', bold: true }
: null,
}
: {}),
...(merged ? { merges: regionMerges(visible) } : {}),
...(pictured
? {
cellImage: (c: CellStyleContext<Row>) =>
c.kind === 'data' && c.column.id === 'level'
? Number(c.row?.qty) >= 20
? dots.many
: dots.few
: null,
}
: {}),
});
say({
ko: `내려받았어요. 서식 ${styled ? '넣음' : '없음'} · 지역 합치기 ${merged ? '켬' : '끔'} · 그림 ${pictured ? '넣음' : '없음'}`,
en: `Downloaded. Styles ${styled ? 'included' : 'none'} · region merge ${merged ? 'on' : 'off'} · picture ${pictured ? 'included' : 'none'}`,
});
},
}; 이 예제는 추가 패키지가 필요해요. 내 컴퓨터에서 돌리려면 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.styled(api, $any($event.target).value)"
>
<option value="on" selected>넣기</option>
<option value="off">빼기</option>
</select>
<select
aria-label="지역 칸 합치기"
[disabled]="!api"
(change)="api && actions.merged(api, $any($event.target).value)"
>
<option value="on" selected>합치기</option>
<option value="off">안 합치기</option>
</select>
<select
aria-label="그림"
[disabled]="!api"
(change)="api && actions.pictured(api, $any($event.target).value)"
>
<option value="on" selected>넣기</option>
<option value="off">빼기</option>
</select>
<button
type="button"
[disabled]="!api"
(click)="api && actions.download(api)"
>내려받기</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 CellStyleContext } 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),
}));
// 머리글 색, 조건에 따른 셀 색·굵게, 같은 지역 셀 합치기(xlsx만), 셀 안 이미지를 담아요.
const sorted = [...rows].sort((a, b) => a.region.localeCompare(b.region, 'ko'));
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: 'level', title: '재고 표시', width: 80, getValue: () => '' },
{
id: 'price',
title: '단가(원)',
kind: 'number',
width: 100,
align: 'end',
formatValue: (v) => Number(v).toLocaleString('ko-KR'),
},
{ id: 'orderedAt', title: '주문일', kind: 'date', width: 110 },
],
rows: sorted,
rowKey: 'id',
};
// 재고 상태 칸: 화면에는 글자 대신 비워 두고, 내보낼 때만 색 동그라미 그림을 넣어요(PNG는 캔버스로 만들어요).
function dot(color: string): string {
const canvas = document.createElement('canvas');
canvas.width = canvas.height = 24;
const g = canvas.getContext('2d');
if (g) {
g.fillStyle = color;
g.beginPath();
g.arc(12, 12, 10, 0, Math.PI * 2);
g.fill();
}
return canvas.toDataURL('image/png');
}
const dots = { many: dot('#dc2626'), few: dot('#16a34a') };
let styled = true;
let merged = true;
let pictured = true;
let say: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
withExport(api);
}
// 지역이 같은 연속된 줄을 찾아 지역 칸을 위아래로 합쳐요.
function regionMerges(list: readonly Row[]) {
const out: { row: number; column: number; rowSpan: number }[] = [];
for (let i = 0; i < list.length;) {
let j = i;
while (j + 1 < list.length && list[j + 1]?.region === list[i]?.region) j += 1;
if (j > i) out.push({ row: i, column: 2, rowSpan: j - i + 1 });
i = j + 1;
}
return out;
}
export const actions = {
styled: (_api: GridApi<Row>, v?: string) => void (styled = v !== 'off'),
merged: (_api: GridApi<Row>, v?: string) => void (merged = v !== 'off'),
pictured: (_api: GridApi<Row>, v?: string) => void (pictured = v !== 'off'),
download: async (api: GridApi<Row>) => {
const ex = withExport(api);
const visible = api.getVisibleRows();
await ex.downloadXlsx('주문-서식.xlsx', {
applyFormatValue: false, // 단가가 글자가 아니라 숫자로 들어가요
...(styled
? {
headerStyle: { background: '#1d4ed8', color: '#ffffff', bold: true },
cellStyle: (c: CellStyleContext<Row>) =>
c.kind === 'data' && c.column.id === 'qty' && Number(c.value) >= 20
? { color: '#b91c1c', bold: true }
: null,
}
: {}),
...(merged ? { merges: regionMerges(visible) } : {}),
...(pictured
? {
cellImage: (c: CellStyleContext<Row>) =>
c.kind === 'data' && c.column.id === 'level'
? Number(c.row?.qty) >= 20
? dots.many
: dots.few
: null,
}
: {}),
});
say({
ko: `내려받았어요. 서식 ${styled ? '넣음' : '없음'} · 지역 합치기 ${merged ? '켬' : '끔'} · 그림 ${pictured ? '넣음' : '없음'}`,
en: `Downloaded. Styles ${styled ? 'included' : 'none'} · region merge ${merged ? 'on' : 'off'} · picture ${pictured ? 'included' : 'none'}`,
});
},
}; 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="Styles" id="styled">
<option value="on" selected>On</option>
<option value="off">Off</option>
</select>
<select aria-label="Merge region cells" id="merged">
<option value="on" selected>On</option>
<option value="off">Off</option>
</select>
<select aria-label="Pictures" id="pictured">
<option value="on" selected>On</option>
<option value="off">Off</option>
</select>
<button type="button" id="download">Download</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('styled').addEventListener('change', (event) => actions.styled(api, event.target.value));
document.getElementById('merged').addEventListener('change', (event) => actions.merged(api, event.target.value));
document.getElementById('pictured').addEventListener('change', (event) => actions.pictured(api, event.target.value));
document.getElementById('download').addEventListener('click', () => actions.download(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),
}));
// Export a header color, conditional cell color and bold, merged cells for the same region (xlsx only) and in-cell images.
const sorted = [...rows].sort((a, b) => a.region.localeCompare(b.region, 'en'));
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: 'level', title: 'Stock flag', width: 90, getValue: () => '' },
{
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: sorted,
rowKey: 'id',
};
// Stock flag column: empty on screen, and only on export a colored dot image is added (the PNG is drawn with a canvas).
function dot(color) {
const canvas = document.createElement('canvas');
canvas.width = canvas.height = 24;
const g = canvas.getContext('2d');
if (g) {
g.fillStyle = color;
g.beginPath();
g.arc(12, 12, 10, 0, Math.PI * 2);
g.fill();
}
return canvas.toDataURL('image/png');
}
const dots = { many: dot('#dc2626'), few: dot('#16a34a') };
let styled = true;
let merged = true;
let pictured = true;
let say = () => { };
export function setup(api, log) {
say = log;
withExport(api);
}
// Find consecutive rows with the same region and merge the region cells vertically.
function regionMerges(list) {
const out = [];
for (let i = 0; i < list.length;) {
let j = i;
while (j + 1 < list.length && list[j + 1]?.region === list[i]?.region)
j += 1;
if (j > i)
out.push({ row: i, column: 2, rowSpan: j - i + 1 });
i = j + 1;
}
return out;
}
export const actions = {
styled: (_api, v) => void (styled = v !== 'off'),
merged: (_api, v) => void (merged = v !== 'off'),
pictured: (_api, v) => void (pictured = v !== 'off'),
download: async (api) => {
const ex = withExport(api);
const visible = api.getVisibleRows();
await ex.downloadXlsx('orders-styled.xlsx', {
applyFormatValue: false, // The price goes in as a number, not text
...(styled
? {
headerStyle: { background: '#1d4ed8', color: '#ffffff', bold: true },
cellStyle: (c) => c.kind === 'data' && c.column.id === 'qty' && Number(c.value) >= 20
? { color: '#b91c1c', bold: true }
: null,
}
: {}),
...(merged ? { merges: regionMerges(visible) } : {}),
...(pictured
? {
cellImage: (c) => c.kind === 'data' && c.column.id === 'level'
? Number(c.row?.qty) >= 20
? dots.many
: dots.few
: null,
}
: {}),
});
say(`Downloaded. Styles ${styled ? 'included' : 'none'} · region merge ${merged ? 'on' : 'off'} · picture ${pictured ? 'included' : 'none'}`);
},
};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 with colors, bold, merged cells and pictures</title>
</head>
<body>
<div class="toolbar">
<select aria-label="Styles" id="styled">
<option value="on" selected>On</option>
<option value="off">Off</option>
</select>
<select aria-label="Merge region cells" id="merged">
<option value="on" selected>On</option>
<option value="off">Off</option>
</select>
<select aria-label="Pictures" id="pictured">
<option value="on" selected>On</option>
<option value="off">Off</option>
</select>
<button type="button" id="download">Download</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),
}));
// Export a header color, conditional cell color and bold, merged cells for the same region (xlsx only) and in-cell images.
const sorted = [...rows].sort((a, b) => a.region.localeCompare(b.region, 'en'));
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: 'level', title: 'Stock flag', width: 90, getValue: () => '' },
{
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: sorted,
rowKey: 'id',
};
// Stock flag column: empty on screen, and only on export a colored dot image is added (the PNG is drawn with a canvas).
function dot(color) {
const canvas = document.createElement('canvas');
canvas.width = canvas.height = 24;
const g = canvas.getContext('2d');
if (g) {
g.fillStyle = color;
g.beginPath();
g.arc(12, 12, 10, 0, Math.PI * 2);
g.fill();
}
return canvas.toDataURL('image/png');
}
const dots = { many: dot('#dc2626'), few: dot('#16a34a') };
let styled = true;
let merged = true;
let pictured = true;
let say = () => { };
function setup(api, log) {
say = log;
withExport(api);
}
// Find consecutive rows with the same region and merge the region cells vertically.
function regionMerges(list) {
const out = [];
for (let i = 0; i < list.length;) {
let j = i;
while (j + 1 < list.length && list[j + 1]?.region === list[i]?.region)
j += 1;
if (j > i)
out.push({ row: i, column: 2, rowSpan: j - i + 1 });
i = j + 1;
}
return out;
}
const actions = {
styled: (_api, v) => void (styled = v !== 'off'),
merged: (_api, v) => void (merged = v !== 'off'),
pictured: (_api, v) => void (pictured = v !== 'off'),
download: async (api) => {
const ex = withExport(api);
const visible = api.getVisibleRows();
await ex.downloadXlsx('orders-styled.xlsx', {
applyFormatValue: false, // The price goes in as a number, not text
...(styled
? {
headerStyle: { background: '#1d4ed8', color: '#ffffff', bold: true },
cellStyle: (c) => c.kind === 'data' && c.column.id === 'qty' && Number(c.value) >= 20
? { color: '#b91c1c', bold: true }
: null,
}
: {}),
...(merged ? { merges: regionMerges(visible) } : {}),
...(pictured
? {
cellImage: (c) => c.kind === 'data' && c.column.id === 'level'
? Number(c.row?.qty) >= 20
? dots.many
: dots.few
: null,
}
: {}),
});
say(`Downloaded. Styles ${styled ? 'included' : 'none'} · region merge ${merged ? 'on' : 'off'} · picture ${pictured ? 'included' : 'none'}`);
},
};
options.ariaLabel = "Export with colors, bold, merged cells and pictures";
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('styled').addEventListener('change', (event) => actions.styled(api, event.target.value));
document.getElementById('merged').addEventListener('change', (event) => actions.merged(api, event.target.value));
document.getElementById('pictured').addEventListener('change', (event) => actions.pictured(api, event.target.value));
document.getElementById('download').addEventListener('click', () => actions.download(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="Styles"
disabled={!api}
onChange={(event) => api && actions.styled(api, event.target.value)}
>
<option value="on">On</option>
<option value="off">Off</option>
</select>
<select defaultValue="on"
aria-label="Merge region cells"
disabled={!api}
onChange={(event) => api && actions.merged(api, event.target.value)}
>
<option value="on">On</option>
<option value="off">Off</option>
</select>
<select defaultValue="on"
aria-label="Pictures"
disabled={!api}
onChange={(event) => api && actions.pictured(api, event.target.value)}
>
<option value="on">On</option>
<option value="off">Off</option>
</select>
<button
type="button"
disabled={!api}
onClick={() => api && actions.download(api)}
>Download</button>
</div>
<Grid style={{ height: 330 }} ref={gridRef} options={options} />
</>
);
}import { withExport, type CellStyleContext } 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),
}));
// Export a header color, conditional cell color and bold, merged cells for the same region (xlsx only) and in-cell images.
const sorted = [...rows].sort((a, b) => a.region.localeCompare(b.region, 'en'));
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: 'level', title: 'Stock flag', width: 90, getValue: () => '' },
{
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: sorted,
rowKey: 'id',
};
// Stock flag column: empty on screen, and only on export a colored dot image is added (the PNG is drawn with a canvas).
function dot(color: string): string {
const canvas = document.createElement('canvas');
canvas.width = canvas.height = 24;
const g = canvas.getContext('2d');
if (g) {
g.fillStyle = color;
g.beginPath();
g.arc(12, 12, 10, 0, Math.PI * 2);
g.fill();
}
return canvas.toDataURL('image/png');
}
const dots = { many: dot('#dc2626'), few: dot('#16a34a') };
let styled = true;
let merged = true;
let pictured = true;
let say: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
withExport(api);
}
// Find consecutive rows with the same region and merge the region cells vertically.
function regionMerges(list: readonly Row[]) {
const out: { row: number; column: number; rowSpan: number }[] = [];
for (let i = 0; i < list.length;) {
let j = i;
while (j + 1 < list.length && list[j + 1]?.region === list[i]?.region) j += 1;
if (j > i) out.push({ row: i, column: 2, rowSpan: j - i + 1 });
i = j + 1;
}
return out;
}
export const actions = {
styled: (_api: GridApi<Row>, v?: string) => void (styled = v !== 'off'),
merged: (_api: GridApi<Row>, v?: string) => void (merged = v !== 'off'),
pictured: (_api: GridApi<Row>, v?: string) => void (pictured = v !== 'off'),
download: async (api: GridApi<Row>) => {
const ex = withExport(api);
const visible = api.getVisibleRows();
await ex.downloadXlsx('orders-styled.xlsx', {
applyFormatValue: false, // The price goes in as a number, not text
...(styled
? {
headerStyle: { background: '#1d4ed8', color: '#ffffff', bold: true },
cellStyle: (c: CellStyleContext<Row>) =>
c.kind === 'data' && c.column.id === 'qty' && Number(c.value) >= 20
? { color: '#b91c1c', bold: true }
: null,
}
: {}),
...(merged ? { merges: regionMerges(visible) } : {}),
...(pictured
? {
cellImage: (c: CellStyleContext<Row>) =>
c.kind === 'data' && c.column.id === 'level'
? Number(c.row?.qty) >= 20
? dots.many
: dots.few
: null,
}
: {}),
});
say(
`Downloaded. Styles ${styled ? 'included' : 'none'} · region merge ${merged ? 'on' : 'off'} · picture ${pictured ? 'included' : 'none'}`,
);
},
}; 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="Styles"
:disabled="!api"
@change="api && actions.styled(api, ($event.target as HTMLSelectElement).value)"
>
<option value="on" selected>On</option>
<option value="off">Off</option>
</select>
<select
aria-label="Merge region cells"
:disabled="!api"
@change="api && actions.merged(api, ($event.target as HTMLSelectElement).value)"
>
<option value="on" selected>On</option>
<option value="off">Off</option>
</select>
<select
aria-label="Pictures"
:disabled="!api"
@change="api && actions.pictured(api, ($event.target as HTMLSelectElement).value)"
>
<option value="on" selected>On</option>
<option value="off">Off</option>
</select>
<button
type="button"
:disabled="!api"
@click="api && actions.download(api)"
>Download</button>
</div>
<Grid style="height: 330px" :options="options" @ready="onReady" />
</template>import { withExport, type CellStyleContext } 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),
}));
// Export a header color, conditional cell color and bold, merged cells for the same region (xlsx only) and in-cell images.
const sorted = [...rows].sort((a, b) => a.region.localeCompare(b.region, 'en'));
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: 'level', title: 'Stock flag', width: 90, getValue: () => '' },
{
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: sorted,
rowKey: 'id',
};
// Stock flag column: empty on screen, and only on export a colored dot image is added (the PNG is drawn with a canvas).
function dot(color: string): string {
const canvas = document.createElement('canvas');
canvas.width = canvas.height = 24;
const g = canvas.getContext('2d');
if (g) {
g.fillStyle = color;
g.beginPath();
g.arc(12, 12, 10, 0, Math.PI * 2);
g.fill();
}
return canvas.toDataURL('image/png');
}
const dots = { many: dot('#dc2626'), few: dot('#16a34a') };
let styled = true;
let merged = true;
let pictured = true;
let say: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
withExport(api);
}
// Find consecutive rows with the same region and merge the region cells vertically.
function regionMerges(list: readonly Row[]) {
const out: { row: number; column: number; rowSpan: number }[] = [];
for (let i = 0; i < list.length;) {
let j = i;
while (j + 1 < list.length && list[j + 1]?.region === list[i]?.region) j += 1;
if (j > i) out.push({ row: i, column: 2, rowSpan: j - i + 1 });
i = j + 1;
}
return out;
}
export const actions = {
styled: (_api: GridApi<Row>, v?: string) => void (styled = v !== 'off'),
merged: (_api: GridApi<Row>, v?: string) => void (merged = v !== 'off'),
pictured: (_api: GridApi<Row>, v?: string) => void (pictured = v !== 'off'),
download: async (api: GridApi<Row>) => {
const ex = withExport(api);
const visible = api.getVisibleRows();
await ex.downloadXlsx('orders-styled.xlsx', {
applyFormatValue: false, // The price goes in as a number, not text
...(styled
? {
headerStyle: { background: '#1d4ed8', color: '#ffffff', bold: true },
cellStyle: (c: CellStyleContext<Row>) =>
c.kind === 'data' && c.column.id === 'qty' && Number(c.value) >= 20
? { color: '#b91c1c', bold: true }
: null,
}
: {}),
...(merged ? { merges: regionMerges(visible) } : {}),
...(pictured
? {
cellImage: (c: CellStyleContext<Row>) =>
c.kind === 'data' && c.column.id === 'level'
? Number(c.row?.qty) >= 20
? dots.many
: dots.few
: null,
}
: {}),
});
say(
`Downloaded. Styles ${styled ? 'included' : 'none'} · region merge ${merged ? 'on' : 'off'} · picture ${pictured ? 'included' : 'none'}`,
);
},
}; 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="Styles"
[disabled]="!api"
(change)="api && actions.styled(api, $any($event.target).value)"
>
<option value="on" selected>On</option>
<option value="off">Off</option>
</select>
<select
aria-label="Merge region cells"
[disabled]="!api"
(change)="api && actions.merged(api, $any($event.target).value)"
>
<option value="on" selected>On</option>
<option value="off">Off</option>
</select>
<select
aria-label="Pictures"
[disabled]="!api"
(change)="api && actions.pictured(api, $any($event.target).value)"
>
<option value="on" selected>On</option>
<option value="off">Off</option>
</select>
<button
type="button"
[disabled]="!api"
(click)="api && actions.download(api)"
>Download</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 CellStyleContext } 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),
}));
// Export a header color, conditional cell color and bold, merged cells for the same region (xlsx only) and in-cell images.
const sorted = [...rows].sort((a, b) => a.region.localeCompare(b.region, 'en'));
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: 'level', title: 'Stock flag', width: 90, getValue: () => '' },
{
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: sorted,
rowKey: 'id',
};
// Stock flag column: empty on screen, and only on export a colored dot image is added (the PNG is drawn with a canvas).
function dot(color: string): string {
const canvas = document.createElement('canvas');
canvas.width = canvas.height = 24;
const g = canvas.getContext('2d');
if (g) {
g.fillStyle = color;
g.beginPath();
g.arc(12, 12, 10, 0, Math.PI * 2);
g.fill();
}
return canvas.toDataURL('image/png');
}
const dots = { many: dot('#dc2626'), few: dot('#16a34a') };
let styled = true;
let merged = true;
let pictured = true;
let say: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
withExport(api);
}
// Find consecutive rows with the same region and merge the region cells vertically.
function regionMerges(list: readonly Row[]) {
const out: { row: number; column: number; rowSpan: number }[] = [];
for (let i = 0; i < list.length;) {
let j = i;
while (j + 1 < list.length && list[j + 1]?.region === list[i]?.region) j += 1;
if (j > i) out.push({ row: i, column: 2, rowSpan: j - i + 1 });
i = j + 1;
}
return out;
}
export const actions = {
styled: (_api: GridApi<Row>, v?: string) => void (styled = v !== 'off'),
merged: (_api: GridApi<Row>, v?: string) => void (merged = v !== 'off'),
pictured: (_api: GridApi<Row>, v?: string) => void (pictured = v !== 'off'),
download: async (api: GridApi<Row>) => {
const ex = withExport(api);
const visible = api.getVisibleRows();
await ex.downloadXlsx('orders-styled.xlsx', {
applyFormatValue: false, // The price goes in as a number, not text
...(styled
? {
headerStyle: { background: '#1d4ed8', color: '#ffffff', bold: true },
cellStyle: (c: CellStyleContext<Row>) =>
c.kind === 'data' && c.column.id === 'qty' && Number(c.value) >= 20
? { color: '#b91c1c', bold: true }
: null,
}
: {}),
...(merged ? { merges: regionMerges(visible) } : {}),
...(pictured
? {
cellImage: (c: CellStyleContext<Row>) =>
c.kind === 'data' && c.column.id === 'level'
? Number(c.row?.qty) >= 20
? dots.many
: dots.few
: null,
}
: {}),
});
say(
`Downloaded. Styles ${styled ? 'included' : 'none'} · region merge ${merged ? 'on' : 'off'} · picture ${pictured ? 'included' : 'none'}`,
);
},
};