머리글 그룹을 엑셀에 병합 셀로 내보내기Export header groups to Excel as merged cells
exportXlsx의 headerGroups: true는 화면의 머리글 그룹을 여러 줄 머리글로 내보내요. 그룹 제목은 가로 병합, 컬럼 머리글은 세로 병합이고 머리글 블록 전체가 고정돼요.headerGroups: true in exportXlsx writes the on-screen header groups as a multi-row header. Group titles merge horizontally, column headers merge vertically, and the whole block is frozen.
코드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="mode">
<option value="on" selected>머리글 그룹 포함</option>
<option value="off">그룹 없이 (한 줄)</option>
</select>
<button type="button" id="preview">시트 미리보기</button>
<button type="button" id="download">내려받기</button>
<button type="button" id="collapse">그룹 접기</button>
<button type="button" id="expand">그룹 펼치기</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('mode').addEventListener('change', (event) => actions.mode(api, event.target.value));
document.getElementById('preview').addEventListener('click', () => actions.preview(api));
document.getElementById('download').addEventListener('click', () => actions.download(api));
document.getElementById('collapse').addEventListener('click', () => actions.collapse(api));
document.getElementById('expand').addEventListener('click', () => actions.expand(api));import { withExport } from '@maxgrid/export';
const en = document.documentElement.dataset.lang === 'en';
const rows = [
{ id: 1, team: en ? 'Sales 1' : '영업 1팀', q1: 120, q2: 135, q3: 150, q4: 170, note: '' },
{
id: 2,
team: en ? 'Sales 2' : '영업 2팀',
q1: 90,
q2: 100,
q3: 95,
q4: 110,
note: en ? 'New client' : '신규 거래처',
},
{ id: 3, team: en ? 'Partners' : '제휴팀', q1: 60, q2: 80, q3: 85, q4: 90, note: '' },
];
// 머리글 그룹(headerGroups)이 세 층이에요: 실적 > 상반기·하반기 > 분기. 화면과 같은 모양으로 내려받으려면
// exportXlsx의 headerGroups: true를 줘요(기본은 그룹 없이 한 줄 머리글이에요).
export const options = {
columns: [
{ id: 'team', title: en ? 'Team' : '팀', width: 120 },
{ id: 'q1', title: en ? 'Q1' : '1분기', kind: 'number', width: 80, align: 'end' },
{ id: 'q2', title: en ? 'Q2' : '2분기', kind: 'number', width: 80, align: 'end' },
{ id: 'q3', title: en ? 'Q3' : '3분기', kind: 'number', width: 80, align: 'end' },
{ id: 'q4', title: en ? 'Q4' : '4분기', kind: 'number', width: 80, align: 'end' },
{ id: 'note', title: en ? 'Note' : '비고', width: 140 },
],
headerGroups: [
{
id: 'perf',
title: en ? 'Results' : '실적',
collapsible: true,
children: [
{ id: 'h1', title: en ? 'First half' : '상반기', children: ['q1', 'q2'] },
{ id: 'h2', title: en ? 'Second half' : '하반기', children: ['q3', 'q4'] },
],
},
],
rows,
rowKey: 'id',
ariaLabel: en ? 'Header group export' : '머리글 그룹 내보내기',
};
let grouped = true;
let say = () => { };
/** 비압축 xlsx의 첫 시트에서 머리글 줄과 병합 범위를 읽어 글자로 보여 줘요. */
function describeSheet(bytes) {
const text = new TextDecoder('utf-8').decode(bytes);
const xml = text.slice(text.search(/xl\/worksheets\/sheet1\.xml<\?xml/));
const frozen = /<pane [^>]*ySplit="(\d+)"/.exec(xml)?.[1] ?? '0';
const merges = [...xml.matchAll(/<mergeCell ref="([^"]+)"/g)].map((m) => m[1]);
const head = [];
for (let r = 1; r <= Number(frozen); r++) {
const line = new RegExp(`<row r="${r}"[^>]*>(.*?)</row>`).exec(xml)?.[1] ?? '';
const cells = [...line.matchAll(/<c r="([A-Z]+)\d+"[^>]*><is><t[^>]*>([^<]*)<\/t>/g)];
head.push(cells.map((c) => `${c[1]}${r}=${c[2]}`).join(' · '));
}
return { head, merges, frozen };
}
export function setup(api, log) {
say = log;
grouped = true;
withExport(api);
log({
ko: '"시트 미리보기"를 누르면 머리글 줄과 병합 범위가 기록에 나와요. 선택에서 "그룹 없이"를 고르면 1.4.0과 같은 한 줄 머리글이에요.',
en: 'Press "Preview sheet" to log the header rows and merge ranges. Choose "Without groups" for the one-row header of 1.4.0.',
});
}
export const actions = {
mode: (_api, v) => void (grouped = v !== 'off'),
preview: (api) => {
const bytes = withExport(api).exportXlsx({ headerGroups: grouped });
const { head, merges, frozen } = describeSheet(bytes);
say({
ko: `머리글 ${frozen}줄(고정) · 병합 ${merges.join(', ') || '없음'}`,
en: `${frozen} header row(s) frozen · merges ${merges.join(', ') || 'none'}`,
});
head.forEach((line, i) => say({ ko: ` ${i + 1}줄: ${line}`, en: ` row ${i + 1}: ${line}` }));
},
download: async (api) => {
await withExport(api).downloadXlsx('실적-머리글그룹.xlsx', { headerGroups: grouped });
say({ ko: '내려받았어요.', en: 'Downloaded.' });
},
collapse: (api) => {
api.setHeaderGroupState({ perf: { collapsed: true } });
say({
ko: '"실적" 그룹을 접었어요. 내보내면 접은 모양(하위 그룹 없이)으로 나가요.',
en: 'Collapsed the "실적" group. The export follows the collapsed shape (no sub-groups).',
});
},
expand: (api) => {
api.resetHeaderGroupState();
say({
ko: '"실적" 그룹을 펼쳤어요. 내보내면 하위 그룹까지 나가요.',
en: 'Expanded the "실적" group. The export includes the sub-groups.',
});
},
}; 이 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="mode">
<option value="on" selected>머리글 그룹 포함</option>
<option value="off">그룹 없이 (한 줄)</option>
</select>
<button type="button" id="preview">시트 미리보기</button>
<button type="button" id="download">내려받기</button>
<button type="button" id="collapse">그룹 접기</button>
<button type="button" id="expand">그룹 펼치기</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 { withExport } = MaxGridExport;
const en = document.documentElement.dataset.lang === 'en';
const rows = [
{ id: 1, team: en ? 'Sales 1' : '영업 1팀', q1: 120, q2: 135, q3: 150, q4: 170, note: '' },
{
id: 2,
team: en ? 'Sales 2' : '영업 2팀',
q1: 90,
q2: 100,
q3: 95,
q4: 110,
note: en ? 'New client' : '신규 거래처',
},
{ id: 3, team: en ? 'Partners' : '제휴팀', q1: 60, q2: 80, q3: 85, q4: 90, note: '' },
];
// 머리글 그룹(headerGroups)이 세 층이에요: 실적 > 상반기·하반기 > 분기. 화면과 같은 모양으로 내려받으려면
// exportXlsx의 headerGroups: true를 줘요(기본은 그룹 없이 한 줄 머리글이에요).
const options = {
columns: [
{ id: 'team', title: en ? 'Team' : '팀', width: 120 },
{ id: 'q1', title: en ? 'Q1' : '1분기', kind: 'number', width: 80, align: 'end' },
{ id: 'q2', title: en ? 'Q2' : '2분기', kind: 'number', width: 80, align: 'end' },
{ id: 'q3', title: en ? 'Q3' : '3분기', kind: 'number', width: 80, align: 'end' },
{ id: 'q4', title: en ? 'Q4' : '4분기', kind: 'number', width: 80, align: 'end' },
{ id: 'note', title: en ? 'Note' : '비고', width: 140 },
],
headerGroups: [
{
id: 'perf',
title: en ? 'Results' : '실적',
collapsible: true,
children: [
{ id: 'h1', title: en ? 'First half' : '상반기', children: ['q1', 'q2'] },
{ id: 'h2', title: en ? 'Second half' : '하반기', children: ['q3', 'q4'] },
],
},
],
rows,
rowKey: 'id',
ariaLabel: en ? 'Header group export' : '머리글 그룹 내보내기',
};
let grouped = true;
let say = () => { };
/** 비압축 xlsx의 첫 시트에서 머리글 줄과 병합 범위를 읽어 글자로 보여 줘요. */
function describeSheet(bytes) {
const text = new TextDecoder('utf-8').decode(bytes);
const xml = text.slice(text.search(/xl\/worksheets\/sheet1\.xml<\?xml/));
const frozen = /<pane [^>]*ySplit="(\d+)"/.exec(xml)?.[1] ?? '0';
const merges = [...xml.matchAll(/<mergeCell ref="([^"]+)"/g)].map((m) => m[1]);
const head = [];
for (let r = 1; r <= Number(frozen); r++) {
const line = new RegExp(`<row r="${r}"[^>]*>(.*?)</row>`).exec(xml)?.[1] ?? '';
const cells = [...line.matchAll(/<c r="([A-Z]+)\d+"[^>]*><is><t[^>]*>([^<]*)<\/t>/g)];
head.push(cells.map((c) => `${c[1]}${r}=${c[2]}`).join(' · '));
}
return { head, merges, frozen };
}
function setup(api, log) {
say = log;
grouped = true;
withExport(api);
log({
ko: '"시트 미리보기"를 누르면 머리글 줄과 병합 범위가 기록에 나와요. 선택에서 "그룹 없이"를 고르면 1.4.0과 같은 한 줄 머리글이에요.',
en: 'Press "Preview sheet" to log the header rows and merge ranges. Choose "Without groups" for the one-row header of 1.4.0.',
});
}
const actions = {
mode: (_api, v) => void (grouped = v !== 'off'),
preview: (api) => {
const bytes = withExport(api).exportXlsx({ headerGroups: grouped });
const { head, merges, frozen } = describeSheet(bytes);
say({
ko: `머리글 ${frozen}줄(고정) · 병합 ${merges.join(', ') || '없음'}`,
en: `${frozen} header row(s) frozen · merges ${merges.join(', ') || 'none'}`,
});
head.forEach((line, i) => say({ ko: ` ${i + 1}줄: ${line}`, en: ` row ${i + 1}: ${line}` }));
},
download: async (api) => {
await withExport(api).downloadXlsx('실적-머리글그룹.xlsx', { headerGroups: grouped });
say({ ko: '내려받았어요.', en: 'Downloaded.' });
},
collapse: (api) => {
api.setHeaderGroupState({ perf: { collapsed: true } });
say({
ko: '"실적" 그룹을 접었어요. 내보내면 접은 모양(하위 그룹 없이)으로 나가요.',
en: 'Collapsed the "실적" group. The export follows the collapsed shape (no sub-groups).',
});
},
expand: (api) => {
api.resetHeaderGroupState();
say({
ko: '"실적" 그룹을 펼쳤어요. 내보내면 하위 그룹까지 나가요.',
en: 'Expanded the "실적" group. The export includes the sub-groups.',
});
},
};
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('mode').addEventListener('change', (event) => actions.mode(api, event.target.value));
document.getElementById('preview').addEventListener('click', () => actions.preview(api));
document.getElementById('download').addEventListener('click', () => actions.download(api));
document.getElementById('collapse').addEventListener('click', () => actions.collapse(api));
document.getElementById('expand').addEventListener('click', () => actions.expand(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.mode(api, event.target.value)}
>
<option value="on">머리글 그룹 포함</option>
<option value="off">그룹 없이 (한 줄)</option>
</select>
<button
type="button"
disabled={!api}
onClick={() => api && actions.preview(api)}
>시트 미리보기</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.download(api)}
>내려받기</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.collapse(api)}
>그룹 접기</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.expand(api)}
>그룹 펼치기</button>
</div>
<Grid style={{ height: 300 }} ref={gridRef} options={options} />
</>
);
}import { withExport } from '@maxgrid/export';
import type { GridApi, GridOptions } from '@maxgrid/react';
const en = document.documentElement.dataset.lang === 'en';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
team: string;
q1: number;
q2: number;
q3: number;
q4: number;
note: string;
}
const rows: Row[] = [
{ id: 1, team: en ? 'Sales 1' : '영업 1팀', q1: 120, q2: 135, q3: 150, q4: 170, note: '' },
{
id: 2,
team: en ? 'Sales 2' : '영업 2팀',
q1: 90,
q2: 100,
q3: 95,
q4: 110,
note: en ? 'New client' : '신규 거래처',
},
{ id: 3, team: en ? 'Partners' : '제휴팀', q1: 60, q2: 80, q3: 85, q4: 90, note: '' },
];
// 머리글 그룹(headerGroups)이 세 층이에요: 실적 > 상반기·하반기 > 분기. 화면과 같은 모양으로 내려받으려면
// exportXlsx의 headerGroups: true를 줘요(기본은 그룹 없이 한 줄 머리글이에요).
export const options: GridOptions<Row> = {
columns: [
{ id: 'team', title: en ? 'Team' : '팀', width: 120 },
{ id: 'q1', title: en ? 'Q1' : '1분기', kind: 'number', width: 80, align: 'end' },
{ id: 'q2', title: en ? 'Q2' : '2분기', kind: 'number', width: 80, align: 'end' },
{ id: 'q3', title: en ? 'Q3' : '3분기', kind: 'number', width: 80, align: 'end' },
{ id: 'q4', title: en ? 'Q4' : '4분기', kind: 'number', width: 80, align: 'end' },
{ id: 'note', title: en ? 'Note' : '비고', width: 140 },
],
headerGroups: [
{
id: 'perf',
title: en ? 'Results' : '실적',
collapsible: true,
children: [
{ id: 'h1', title: en ? 'First half' : '상반기', children: ['q1', 'q2'] },
{ id: 'h2', title: en ? 'Second half' : '하반기', children: ['q3', 'q4'] },
],
},
],
rows,
rowKey: 'id',
ariaLabel: en ? 'Header group export' : '머리글 그룹 내보내기',
};
let grouped = true;
let say: (message: LogText) => void = () => {};
/** 비압축 xlsx의 첫 시트에서 머리글 줄과 병합 범위를 읽어 글자로 보여 줘요. */
function describeSheet(bytes: Uint8Array): { head: string[]; merges: string[]; frozen: string } {
const text = new TextDecoder('utf-8').decode(bytes);
const xml = text.slice(text.search(/xl\/worksheets\/sheet1\.xml<\?xml/));
const frozen = /<pane [^>]*ySplit="(\d+)"/.exec(xml)?.[1] ?? '0';
const merges = [...xml.matchAll(/<mergeCell ref="([^"]+)"/g)].map((m) => m[1] as string);
const head: string[] = [];
for (let r = 1; r <= Number(frozen); r++) {
const line = new RegExp(`<row r="${r}"[^>]*>(.*?)</row>`).exec(xml)?.[1] ?? '';
const cells = [...line.matchAll(/<c r="([A-Z]+)\d+"[^>]*><is><t[^>]*>([^<]*)<\/t>/g)];
head.push(cells.map((c) => `${c[1]}${r}=${c[2]}`).join(' · '));
}
return { head, merges, frozen };
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
grouped = true;
withExport(api);
log({
ko: '"시트 미리보기"를 누르면 머리글 줄과 병합 범위가 기록에 나와요. 선택에서 "그룹 없이"를 고르면 1.4.0과 같은 한 줄 머리글이에요.',
en: 'Press "Preview sheet" to log the header rows and merge ranges. Choose "Without groups" for the one-row header of 1.4.0.',
});
}
export const actions = {
mode: (_api: GridApi<Row>, v?: string) => void (grouped = v !== 'off'),
preview: (api: GridApi<Row>) => {
const bytes = withExport(api).exportXlsx({ headerGroups: grouped });
const { head, merges, frozen } = describeSheet(bytes);
say({
ko: `머리글 ${frozen}줄(고정) · 병합 ${merges.join(', ') || '없음'}`,
en: `${frozen} header row(s) frozen · merges ${merges.join(', ') || 'none'}`,
});
head.forEach((line, i) => say({ ko: ` ${i + 1}줄: ${line}`, en: ` row ${i + 1}: ${line}` }));
},
download: async (api: GridApi<Row>) => {
await withExport(api).downloadXlsx('실적-머리글그룹.xlsx', { headerGroups: grouped });
say({ ko: '내려받았어요.', en: 'Downloaded.' });
},
collapse: (api: GridApi<Row>) => {
api.setHeaderGroupState({ perf: { collapsed: true } });
say({
ko: '"실적" 그룹을 접었어요. 내보내면 접은 모양(하위 그룹 없이)으로 나가요.',
en: 'Collapsed the "실적" group. The export follows the collapsed shape (no sub-groups).',
});
},
expand: (api: GridApi<Row>) => {
api.resetHeaderGroupState();
say({
ko: '"실적" 그룹을 펼쳤어요. 내보내면 하위 그룹까지 나가요.',
en: 'Expanded the "실적" group. The export includes the sub-groups.',
});
},
}; 이 예제는 추가 패키지가 필요해요. 내 컴퓨터에서 돌리려면 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.mode(api, ($event.target as HTMLSelectElement).value)"
>
<option value="on" selected>머리글 그룹 포함</option>
<option value="off">그룹 없이 (한 줄)</option>
</select>
<button type="button" :disabled="!api" @click="api && actions.preview(api)">시트 미리보기</button>
<button
type="button"
:disabled="!api"
@click="api && actions.download(api)"
>내려받기</button>
<button
type="button"
:disabled="!api"
@click="api && actions.collapse(api)"
>그룹 접기</button>
<button type="button" :disabled="!api" @click="api && actions.expand(api)">그룹 펼치기</button>
</div>
<Grid style="height: 300px" :options="options" @ready="onReady" />
</template>import { withExport } from '@maxgrid/export';
import type { GridApi, GridOptions } from '@maxgrid/vue';
const en = document.documentElement.dataset.lang === 'en';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
team: string;
q1: number;
q2: number;
q3: number;
q4: number;
note: string;
}
const rows: Row[] = [
{ id: 1, team: en ? 'Sales 1' : '영업 1팀', q1: 120, q2: 135, q3: 150, q4: 170, note: '' },
{
id: 2,
team: en ? 'Sales 2' : '영업 2팀',
q1: 90,
q2: 100,
q3: 95,
q4: 110,
note: en ? 'New client' : '신규 거래처',
},
{ id: 3, team: en ? 'Partners' : '제휴팀', q1: 60, q2: 80, q3: 85, q4: 90, note: '' },
];
// 머리글 그룹(headerGroups)이 세 층이에요: 실적 > 상반기·하반기 > 분기. 화면과 같은 모양으로 내려받으려면
// exportXlsx의 headerGroups: true를 줘요(기본은 그룹 없이 한 줄 머리글이에요).
export const options: GridOptions<Row> = {
columns: [
{ id: 'team', title: en ? 'Team' : '팀', width: 120 },
{ id: 'q1', title: en ? 'Q1' : '1분기', kind: 'number', width: 80, align: 'end' },
{ id: 'q2', title: en ? 'Q2' : '2분기', kind: 'number', width: 80, align: 'end' },
{ id: 'q3', title: en ? 'Q3' : '3분기', kind: 'number', width: 80, align: 'end' },
{ id: 'q4', title: en ? 'Q4' : '4분기', kind: 'number', width: 80, align: 'end' },
{ id: 'note', title: en ? 'Note' : '비고', width: 140 },
],
headerGroups: [
{
id: 'perf',
title: en ? 'Results' : '실적',
collapsible: true,
children: [
{ id: 'h1', title: en ? 'First half' : '상반기', children: ['q1', 'q2'] },
{ id: 'h2', title: en ? 'Second half' : '하반기', children: ['q3', 'q4'] },
],
},
],
rows,
rowKey: 'id',
ariaLabel: en ? 'Header group export' : '머리글 그룹 내보내기',
};
let grouped = true;
let say: (message: LogText) => void = () => {};
/** 비압축 xlsx의 첫 시트에서 머리글 줄과 병합 범위를 읽어 글자로 보여 줘요. */
function describeSheet(bytes: Uint8Array): { head: string[]; merges: string[]; frozen: string } {
const text = new TextDecoder('utf-8').decode(bytes);
const xml = text.slice(text.search(/xl\/worksheets\/sheet1\.xml<\?xml/));
const frozen = /<pane [^>]*ySplit="(\d+)"/.exec(xml)?.[1] ?? '0';
const merges = [...xml.matchAll(/<mergeCell ref="([^"]+)"/g)].map((m) => m[1] as string);
const head: string[] = [];
for (let r = 1; r <= Number(frozen); r++) {
const line = new RegExp(`<row r="${r}"[^>]*>(.*?)</row>`).exec(xml)?.[1] ?? '';
const cells = [...line.matchAll(/<c r="([A-Z]+)\d+"[^>]*><is><t[^>]*>([^<]*)<\/t>/g)];
head.push(cells.map((c) => `${c[1]}${r}=${c[2]}`).join(' · '));
}
return { head, merges, frozen };
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
grouped = true;
withExport(api);
log({
ko: '"시트 미리보기"를 누르면 머리글 줄과 병합 범위가 기록에 나와요. 선택에서 "그룹 없이"를 고르면 1.4.0과 같은 한 줄 머리글이에요.',
en: 'Press "Preview sheet" to log the header rows and merge ranges. Choose "Without groups" for the one-row header of 1.4.0.',
});
}
export const actions = {
mode: (_api: GridApi<Row>, v?: string) => void (grouped = v !== 'off'),
preview: (api: GridApi<Row>) => {
const bytes = withExport(api).exportXlsx({ headerGroups: grouped });
const { head, merges, frozen } = describeSheet(bytes);
say({
ko: `머리글 ${frozen}줄(고정) · 병합 ${merges.join(', ') || '없음'}`,
en: `${frozen} header row(s) frozen · merges ${merges.join(', ') || 'none'}`,
});
head.forEach((line, i) => say({ ko: ` ${i + 1}줄: ${line}`, en: ` row ${i + 1}: ${line}` }));
},
download: async (api: GridApi<Row>) => {
await withExport(api).downloadXlsx('실적-머리글그룹.xlsx', { headerGroups: grouped });
say({ ko: '내려받았어요.', en: 'Downloaded.' });
},
collapse: (api: GridApi<Row>) => {
api.setHeaderGroupState({ perf: { collapsed: true } });
say({
ko: '"실적" 그룹을 접었어요. 내보내면 접은 모양(하위 그룹 없이)으로 나가요.',
en: 'Collapsed the "실적" group. The export follows the collapsed shape (no sub-groups).',
});
},
expand: (api: GridApi<Row>) => {
api.resetHeaderGroupState();
say({
ko: '"실적" 그룹을 펼쳤어요. 내보내면 하위 그룹까지 나가요.',
en: 'Expanded the "실적" group. The export includes the sub-groups.',
});
},
}; 이 예제는 추가 패키지가 필요해요. 내 컴퓨터에서 돌리려면 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.mode(api, $any($event.target).value)"
>
<option value="on" selected>머리글 그룹 포함</option>
<option value="off">그룹 없이 (한 줄)</option>
</select>
<button
type="button"
[disabled]="!api"
(click)="api && actions.preview(api)"
>시트 미리보기</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.download(api)"
>내려받기</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.collapse(api)"
>그룹 접기</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.expand(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 { withExport } from '@maxgrid/export';
import type { GridApi, GridOptions } from '@maxgrid/angular';
const en = document.documentElement.dataset.lang === 'en';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
team: string;
q1: number;
q2: number;
q3: number;
q4: number;
note: string;
}
const rows: Row[] = [
{ id: 1, team: en ? 'Sales 1' : '영업 1팀', q1: 120, q2: 135, q3: 150, q4: 170, note: '' },
{
id: 2,
team: en ? 'Sales 2' : '영업 2팀',
q1: 90,
q2: 100,
q3: 95,
q4: 110,
note: en ? 'New client' : '신규 거래처',
},
{ id: 3, team: en ? 'Partners' : '제휴팀', q1: 60, q2: 80, q3: 85, q4: 90, note: '' },
];
// 머리글 그룹(headerGroups)이 세 층이에요: 실적 > 상반기·하반기 > 분기. 화면과 같은 모양으로 내려받으려면
// exportXlsx의 headerGroups: true를 줘요(기본은 그룹 없이 한 줄 머리글이에요).
export const options: GridOptions<Row> = {
columns: [
{ id: 'team', title: en ? 'Team' : '팀', width: 120 },
{ id: 'q1', title: en ? 'Q1' : '1분기', kind: 'number', width: 80, align: 'end' },
{ id: 'q2', title: en ? 'Q2' : '2분기', kind: 'number', width: 80, align: 'end' },
{ id: 'q3', title: en ? 'Q3' : '3분기', kind: 'number', width: 80, align: 'end' },
{ id: 'q4', title: en ? 'Q4' : '4분기', kind: 'number', width: 80, align: 'end' },
{ id: 'note', title: en ? 'Note' : '비고', width: 140 },
],
headerGroups: [
{
id: 'perf',
title: en ? 'Results' : '실적',
collapsible: true,
children: [
{ id: 'h1', title: en ? 'First half' : '상반기', children: ['q1', 'q2'] },
{ id: 'h2', title: en ? 'Second half' : '하반기', children: ['q3', 'q4'] },
],
},
],
rows,
rowKey: 'id',
ariaLabel: en ? 'Header group export' : '머리글 그룹 내보내기',
};
let grouped = true;
let say: (message: LogText) => void = () => {};
/** 비압축 xlsx의 첫 시트에서 머리글 줄과 병합 범위를 읽어 글자로 보여 줘요. */
function describeSheet(bytes: Uint8Array): { head: string[]; merges: string[]; frozen: string } {
const text = new TextDecoder('utf-8').decode(bytes);
const xml = text.slice(text.search(/xl\/worksheets\/sheet1\.xml<\?xml/));
const frozen = /<pane [^>]*ySplit="(\d+)"/.exec(xml)?.[1] ?? '0';
const merges = [...xml.matchAll(/<mergeCell ref="([^"]+)"/g)].map((m) => m[1] as string);
const head: string[] = [];
for (let r = 1; r <= Number(frozen); r++) {
const line = new RegExp(`<row r="${r}"[^>]*>(.*?)</row>`).exec(xml)?.[1] ?? '';
const cells = [...line.matchAll(/<c r="([A-Z]+)\d+"[^>]*><is><t[^>]*>([^<]*)<\/t>/g)];
head.push(cells.map((c) => `${c[1]}${r}=${c[2]}`).join(' · '));
}
return { head, merges, frozen };
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
grouped = true;
withExport(api);
log({
ko: '"시트 미리보기"를 누르면 머리글 줄과 병합 범위가 기록에 나와요. 선택에서 "그룹 없이"를 고르면 1.4.0과 같은 한 줄 머리글이에요.',
en: 'Press "Preview sheet" to log the header rows and merge ranges. Choose "Without groups" for the one-row header of 1.4.0.',
});
}
export const actions = {
mode: (_api: GridApi<Row>, v?: string) => void (grouped = v !== 'off'),
preview: (api: GridApi<Row>) => {
const bytes = withExport(api).exportXlsx({ headerGroups: grouped });
const { head, merges, frozen } = describeSheet(bytes);
say({
ko: `머리글 ${frozen}줄(고정) · 병합 ${merges.join(', ') || '없음'}`,
en: `${frozen} header row(s) frozen · merges ${merges.join(', ') || 'none'}`,
});
head.forEach((line, i) => say({ ko: ` ${i + 1}줄: ${line}`, en: ` row ${i + 1}: ${line}` }));
},
download: async (api: GridApi<Row>) => {
await withExport(api).downloadXlsx('실적-머리글그룹.xlsx', { headerGroups: grouped });
say({ ko: '내려받았어요.', en: 'Downloaded.' });
},
collapse: (api: GridApi<Row>) => {
api.setHeaderGroupState({ perf: { collapsed: true } });
say({
ko: '"실적" 그룹을 접었어요. 내보내면 접은 모양(하위 그룹 없이)으로 나가요.',
en: 'Collapsed the "실적" group. The export follows the collapsed shape (no sub-groups).',
});
},
expand: (api: GridApi<Row>) => {
api.resetHeaderGroupState();
say({
ko: '"실적" 그룹을 펼쳤어요. 내보내면 하위 그룹까지 나가요.',
en: 'Expanded the "실적" group. The export includes the sub-groups.',
});
},
}; 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="Export shape" id="mode">
<option value="on" selected>With header groups</option>
<option value="off">Without groups (one row)</option>
</select>
<button type="button" id="preview">Preview sheet</button>
<button type="button" id="download">Download</button>
<button type="button" id="collapse">Collapse group</button>
<button type="button" id="expand">Expand group</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('mode').addEventListener('change', (event) => actions.mode(api, event.target.value));
document.getElementById('preview').addEventListener('click', () => actions.preview(api));
document.getElementById('download').addEventListener('click', () => actions.download(api));
document.getElementById('collapse').addEventListener('click', () => actions.collapse(api));
document.getElementById('expand').addEventListener('click', () => actions.expand(api));import { withExport } from '@maxgrid/export';
const rows = [
{ id: 1, team: 'Sales 1', q1: 120, q2: 135, q3: 150, q4: 170, note: '' },
{ id: 2, team: 'Sales 2', q1: 90, q2: 100, q3: 95, q4: 110, note: 'New client' },
{ id: 3, team: 'Partners', q1: 60, q2: 80, q3: 85, q4: 90, note: '' },
];
// The header groups (headerGroups) have three levels: Results > first/second half > quarter. To download the same shape as
// the screen, pass headerGroups: true to exportXlsx (the default is a one-row header without groups).
export const options = {
columns: [
{ id: 'team', title: 'Team', width: 120 },
{ id: 'q1', title: 'Q1', kind: 'number', width: 80, align: 'end' },
{ id: 'q2', title: 'Q2', kind: 'number', width: 80, align: 'end' },
{ id: 'q3', title: 'Q3', kind: 'number', width: 80, align: 'end' },
{ id: 'q4', title: 'Q4', kind: 'number', width: 80, align: 'end' },
{ id: 'note', title: 'Note', width: 140 },
],
headerGroups: [
{
id: 'perf',
title: 'Results',
collapsible: true,
children: [
{ id: 'h1', title: 'First half', children: ['q1', 'q2'] },
{ id: 'h2', title: 'Second half', children: ['q3', 'q4'] },
],
},
],
rows,
rowKey: 'id',
ariaLabel: 'Header group export',
};
let grouped = true;
let say = () => { };
/** Read the header rows and merge ranges from the first sheet of an uncompressed xlsx and show them as text. */
function describeSheet(bytes) {
const text = new TextDecoder('utf-8').decode(bytes);
const xml = text.slice(text.search(/xl\/worksheets\/sheet1\.xml<\?xml/));
const frozen = /<pane [^>]*ySplit="(\d+)"/.exec(xml)?.[1] ?? '0';
const merges = [...xml.matchAll(/<mergeCell ref="([^"]+)"/g)].map((m) => m[1]);
const head = [];
for (let r = 1; r <= Number(frozen); r++) {
const line = new RegExp(`<row r="${r}"[^>]*>(.*?)</row>`).exec(xml)?.[1] ?? '';
const cells = [...line.matchAll(/<c r="([A-Z]+)\d+"[^>]*><is><t[^>]*>([^<]*)<\/t>/g)];
head.push(cells.map((c) => `${c[1]}${r}=${c[2]}`).join(' · '));
}
return { head, merges, frozen };
}
export function setup(api, log) {
say = log;
grouped = true;
withExport(api);
log('Press "Preview sheet" to log the header rows and merge ranges. Choose "Without groups" for the one-row header of 1.4.0.');
}
export const actions = {
mode: (_api, v) => void (grouped = v !== 'off'),
preview: (api) => {
const bytes = withExport(api).exportXlsx({ headerGroups: grouped });
const { head, merges, frozen } = describeSheet(bytes);
say(`${frozen} header row(s) frozen · merges ${merges.join(', ') || 'none'}`);
head.forEach((line, i) => say(` row ${i + 1}: ${line}`));
},
download: async (api) => {
await withExport(api).downloadXlsx('results-header-groups.xlsx', { headerGroups: grouped });
say('Downloaded.');
},
collapse: (api) => {
api.setHeaderGroupState({ perf: { collapsed: true } });
say('Collapsed the "Results" group. The export follows the collapsed shape (no sub-groups).');
},
expand: (api) => {
api.resetHeaderGroupState();
say('Expanded the "Results" group. The export includes the sub-groups.');
},
};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 header groups to Excel as merged cells</title>
</head>
<body>
<div class="toolbar">
<select aria-label="Export shape" id="mode">
<option value="on" selected>With header groups</option>
<option value="off">Without groups (one row)</option>
</select>
<button type="button" id="preview">Preview sheet</button>
<button type="button" id="download">Download</button>
<button type="button" id="collapse">Collapse group</button>
<button type="button" id="expand">Expand group</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 { withExport } = MaxGridExport;
const rows = [
{ id: 1, team: 'Sales 1', q1: 120, q2: 135, q3: 150, q4: 170, note: '' },
{ id: 2, team: 'Sales 2', q1: 90, q2: 100, q3: 95, q4: 110, note: 'New client' },
{ id: 3, team: 'Partners', q1: 60, q2: 80, q3: 85, q4: 90, note: '' },
];
// The header groups (headerGroups) have three levels: Results > first/second half > quarter. To download the same shape as
// the screen, pass headerGroups: true to exportXlsx (the default is a one-row header without groups).
const options = {
columns: [
{ id: 'team', title: 'Team', width: 120 },
{ id: 'q1', title: 'Q1', kind: 'number', width: 80, align: 'end' },
{ id: 'q2', title: 'Q2', kind: 'number', width: 80, align: 'end' },
{ id: 'q3', title: 'Q3', kind: 'number', width: 80, align: 'end' },
{ id: 'q4', title: 'Q4', kind: 'number', width: 80, align: 'end' },
{ id: 'note', title: 'Note', width: 140 },
],
headerGroups: [
{
id: 'perf',
title: 'Results',
collapsible: true,
children: [
{ id: 'h1', title: 'First half', children: ['q1', 'q2'] },
{ id: 'h2', title: 'Second half', children: ['q3', 'q4'] },
],
},
],
rows,
rowKey: 'id',
ariaLabel: 'Header group export',
};
let grouped = true;
let say = () => { };
/** Read the header rows and merge ranges from the first sheet of an uncompressed xlsx and show them as text. */
function describeSheet(bytes) {
const text = new TextDecoder('utf-8').decode(bytes);
const xml = text.slice(text.search(/xl\/worksheets\/sheet1\.xml<\?xml/));
const frozen = /<pane [^>]*ySplit="(\d+)"/.exec(xml)?.[1] ?? '0';
const merges = [...xml.matchAll(/<mergeCell ref="([^"]+)"/g)].map((m) => m[1]);
const head = [];
for (let r = 1; r <= Number(frozen); r++) {
const line = new RegExp(`<row r="${r}"[^>]*>(.*?)</row>`).exec(xml)?.[1] ?? '';
const cells = [...line.matchAll(/<c r="([A-Z]+)\d+"[^>]*><is><t[^>]*>([^<]*)<\/t>/g)];
head.push(cells.map((c) => `${c[1]}${r}=${c[2]}`).join(' · '));
}
return { head, merges, frozen };
}
function setup(api, log) {
say = log;
grouped = true;
withExport(api);
log('Press "Preview sheet" to log the header rows and merge ranges. Choose "Without groups" for the one-row header of 1.4.0.');
}
const actions = {
mode: (_api, v) => void (grouped = v !== 'off'),
preview: (api) => {
const bytes = withExport(api).exportXlsx({ headerGroups: grouped });
const { head, merges, frozen } = describeSheet(bytes);
say(`${frozen} header row(s) frozen · merges ${merges.join(', ') || 'none'}`);
head.forEach((line, i) => say(` row ${i + 1}: ${line}`));
},
download: async (api) => {
await withExport(api).downloadXlsx('results-header-groups.xlsx', { headerGroups: grouped });
say('Downloaded.');
},
collapse: (api) => {
api.setHeaderGroupState({ perf: { collapsed: true } });
say('Collapsed the "Results" group. The export follows the collapsed shape (no sub-groups).');
},
expand: (api) => {
api.resetHeaderGroupState();
say('Expanded the "Results" group. The export includes the sub-groups.');
},
};
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('mode').addEventListener('change', (event) => actions.mode(api, event.target.value));
document.getElementById('preview').addEventListener('click', () => actions.preview(api));
document.getElementById('download').addEventListener('click', () => actions.download(api));
document.getElementById('collapse').addEventListener('click', () => actions.collapse(api));
document.getElementById('expand').addEventListener('click', () => actions.expand(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="Export shape"
disabled={!api}
onChange={(event) => api && actions.mode(api, event.target.value)}
>
<option value="on">With header groups</option>
<option value="off">Without groups (one row)</option>
</select>
<button
type="button"
disabled={!api}
onClick={() => api && actions.preview(api)}
>Preview sheet</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.download(api)}
>Download</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.collapse(api)}
>Collapse group</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.expand(api)}
>Expand group</button>
</div>
<Grid style={{ height: 300 }} ref={gridRef} options={options} />
</>
);
}import { withExport } from '@maxgrid/export';
import type { GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string;
export interface Row {
id: number;
team: string;
q1: number;
q2: number;
q3: number;
q4: number;
note: string;
}
const rows: Row[] = [
{ id: 1, team: 'Sales 1', q1: 120, q2: 135, q3: 150, q4: 170, note: '' },
{ id: 2, team: 'Sales 2', q1: 90, q2: 100, q3: 95, q4: 110, note: 'New client' },
{ id: 3, team: 'Partners', q1: 60, q2: 80, q3: 85, q4: 90, note: '' },
];
// The header groups (headerGroups) have three levels: Results > first/second half > quarter. To download the same shape as
// the screen, pass headerGroups: true to exportXlsx (the default is a one-row header without groups).
export const options: GridOptions<Row> = {
columns: [
{ id: 'team', title: 'Team', width: 120 },
{ id: 'q1', title: 'Q1', kind: 'number', width: 80, align: 'end' },
{ id: 'q2', title: 'Q2', kind: 'number', width: 80, align: 'end' },
{ id: 'q3', title: 'Q3', kind: 'number', width: 80, align: 'end' },
{ id: 'q4', title: 'Q4', kind: 'number', width: 80, align: 'end' },
{ id: 'note', title: 'Note', width: 140 },
],
headerGroups: [
{
id: 'perf',
title: 'Results',
collapsible: true,
children: [
{ id: 'h1', title: 'First half', children: ['q1', 'q2'] },
{ id: 'h2', title: 'Second half', children: ['q3', 'q4'] },
],
},
],
rows,
rowKey: 'id',
ariaLabel: 'Header group export',
};
let grouped = true;
let say: (message: LogText) => void = () => {};
/** Read the header rows and merge ranges from the first sheet of an uncompressed xlsx and show them as text. */
function describeSheet(bytes: Uint8Array): { head: string[]; merges: string[]; frozen: string } {
const text = new TextDecoder('utf-8').decode(bytes);
const xml = text.slice(text.search(/xl\/worksheets\/sheet1\.xml<\?xml/));
const frozen = /<pane [^>]*ySplit="(\d+)"/.exec(xml)?.[1] ?? '0';
const merges = [...xml.matchAll(/<mergeCell ref="([^"]+)"/g)].map((m) => m[1] as string);
const head: string[] = [];
for (let r = 1; r <= Number(frozen); r++) {
const line = new RegExp(`<row r="${r}"[^>]*>(.*?)</row>`).exec(xml)?.[1] ?? '';
const cells = [...line.matchAll(/<c r="([A-Z]+)\d+"[^>]*><is><t[^>]*>([^<]*)<\/t>/g)];
head.push(cells.map((c) => `${c[1]}${r}=${c[2]}`).join(' · '));
}
return { head, merges, frozen };
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
grouped = true;
withExport(api);
log(
'Press "Preview sheet" to log the header rows and merge ranges. Choose "Without groups" for the one-row header of 1.4.0.',
);
}
export const actions = {
mode: (_api: GridApi<Row>, v?: string) => void (grouped = v !== 'off'),
preview: (api: GridApi<Row>) => {
const bytes = withExport(api).exportXlsx({ headerGroups: grouped });
const { head, merges, frozen } = describeSheet(bytes);
say(`${frozen} header row(s) frozen · merges ${merges.join(', ') || 'none'}`);
head.forEach((line, i) => say(` row ${i + 1}: ${line}`));
},
download: async (api: GridApi<Row>) => {
await withExport(api).downloadXlsx('results-header-groups.xlsx', { headerGroups: grouped });
say('Downloaded.');
},
collapse: (api: GridApi<Row>) => {
api.setHeaderGroupState({ perf: { collapsed: true } });
say('Collapsed the "Results" group. The export follows the collapsed shape (no sub-groups).');
},
expand: (api: GridApi<Row>) => {
api.resetHeaderGroupState();
say('Expanded the "Results" group. The export includes the sub-groups.');
},
}; 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="Export shape"
:disabled="!api"
@change="api && actions.mode(api, ($event.target as HTMLSelectElement).value)"
>
<option value="on" selected>With header groups</option>
<option value="off">Without groups (one row)</option>
</select>
<button type="button" :disabled="!api" @click="api && actions.preview(api)">Preview sheet</button>
<button
type="button"
:disabled="!api"
@click="api && actions.download(api)"
>Download</button>
<button
type="button"
:disabled="!api"
@click="api && actions.collapse(api)"
>Collapse group</button>
<button type="button" :disabled="!api" @click="api && actions.expand(api)">Expand group</button>
</div>
<Grid style="height: 300px" :options="options" @ready="onReady" />
</template>import { withExport } from '@maxgrid/export';
import type { GridApi, GridOptions } from '@maxgrid/vue';
export type LogText = string;
export interface Row {
id: number;
team: string;
q1: number;
q2: number;
q3: number;
q4: number;
note: string;
}
const rows: Row[] = [
{ id: 1, team: 'Sales 1', q1: 120, q2: 135, q3: 150, q4: 170, note: '' },
{ id: 2, team: 'Sales 2', q1: 90, q2: 100, q3: 95, q4: 110, note: 'New client' },
{ id: 3, team: 'Partners', q1: 60, q2: 80, q3: 85, q4: 90, note: '' },
];
// The header groups (headerGroups) have three levels: Results > first/second half > quarter. To download the same shape as
// the screen, pass headerGroups: true to exportXlsx (the default is a one-row header without groups).
export const options: GridOptions<Row> = {
columns: [
{ id: 'team', title: 'Team', width: 120 },
{ id: 'q1', title: 'Q1', kind: 'number', width: 80, align: 'end' },
{ id: 'q2', title: 'Q2', kind: 'number', width: 80, align: 'end' },
{ id: 'q3', title: 'Q3', kind: 'number', width: 80, align: 'end' },
{ id: 'q4', title: 'Q4', kind: 'number', width: 80, align: 'end' },
{ id: 'note', title: 'Note', width: 140 },
],
headerGroups: [
{
id: 'perf',
title: 'Results',
collapsible: true,
children: [
{ id: 'h1', title: 'First half', children: ['q1', 'q2'] },
{ id: 'h2', title: 'Second half', children: ['q3', 'q4'] },
],
},
],
rows,
rowKey: 'id',
ariaLabel: 'Header group export',
};
let grouped = true;
let say: (message: LogText) => void = () => {};
/** Read the header rows and merge ranges from the first sheet of an uncompressed xlsx and show them as text. */
function describeSheet(bytes: Uint8Array): { head: string[]; merges: string[]; frozen: string } {
const text = new TextDecoder('utf-8').decode(bytes);
const xml = text.slice(text.search(/xl\/worksheets\/sheet1\.xml<\?xml/));
const frozen = /<pane [^>]*ySplit="(\d+)"/.exec(xml)?.[1] ?? '0';
const merges = [...xml.matchAll(/<mergeCell ref="([^"]+)"/g)].map((m) => m[1] as string);
const head: string[] = [];
for (let r = 1; r <= Number(frozen); r++) {
const line = new RegExp(`<row r="${r}"[^>]*>(.*?)</row>`).exec(xml)?.[1] ?? '';
const cells = [...line.matchAll(/<c r="([A-Z]+)\d+"[^>]*><is><t[^>]*>([^<]*)<\/t>/g)];
head.push(cells.map((c) => `${c[1]}${r}=${c[2]}`).join(' · '));
}
return { head, merges, frozen };
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
grouped = true;
withExport(api);
log(
'Press "Preview sheet" to log the header rows and merge ranges. Choose "Without groups" for the one-row header of 1.4.0.',
);
}
export const actions = {
mode: (_api: GridApi<Row>, v?: string) => void (grouped = v !== 'off'),
preview: (api: GridApi<Row>) => {
const bytes = withExport(api).exportXlsx({ headerGroups: grouped });
const { head, merges, frozen } = describeSheet(bytes);
say(`${frozen} header row(s) frozen · merges ${merges.join(', ') || 'none'}`);
head.forEach((line, i) => say(` row ${i + 1}: ${line}`));
},
download: async (api: GridApi<Row>) => {
await withExport(api).downloadXlsx('results-header-groups.xlsx', { headerGroups: grouped });
say('Downloaded.');
},
collapse: (api: GridApi<Row>) => {
api.setHeaderGroupState({ perf: { collapsed: true } });
say('Collapsed the "Results" group. The export follows the collapsed shape (no sub-groups).');
},
expand: (api: GridApi<Row>) => {
api.resetHeaderGroupState();
say('Expanded the "Results" group. The export includes the sub-groups.');
},
}; 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="Export shape"
[disabled]="!api"
(change)="api && actions.mode(api, $any($event.target).value)"
>
<option value="on" selected>With header groups</option>
<option value="off">Without groups (one row)</option>
</select>
<button
type="button"
[disabled]="!api"
(click)="api && actions.preview(api)"
>Preview sheet</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.download(api)"
>Download</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.collapse(api)"
>Collapse group</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.expand(api)"
>Expand group</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 { withExport } from '@maxgrid/export';
import type { GridApi, GridOptions } from '@maxgrid/angular';
export type LogText = string;
export interface Row {
id: number;
team: string;
q1: number;
q2: number;
q3: number;
q4: number;
note: string;
}
const rows: Row[] = [
{ id: 1, team: 'Sales 1', q1: 120, q2: 135, q3: 150, q4: 170, note: '' },
{ id: 2, team: 'Sales 2', q1: 90, q2: 100, q3: 95, q4: 110, note: 'New client' },
{ id: 3, team: 'Partners', q1: 60, q2: 80, q3: 85, q4: 90, note: '' },
];
// The header groups (headerGroups) have three levels: Results > first/second half > quarter. To download the same shape as
// the screen, pass headerGroups: true to exportXlsx (the default is a one-row header without groups).
export const options: GridOptions<Row> = {
columns: [
{ id: 'team', title: 'Team', width: 120 },
{ id: 'q1', title: 'Q1', kind: 'number', width: 80, align: 'end' },
{ id: 'q2', title: 'Q2', kind: 'number', width: 80, align: 'end' },
{ id: 'q3', title: 'Q3', kind: 'number', width: 80, align: 'end' },
{ id: 'q4', title: 'Q4', kind: 'number', width: 80, align: 'end' },
{ id: 'note', title: 'Note', width: 140 },
],
headerGroups: [
{
id: 'perf',
title: 'Results',
collapsible: true,
children: [
{ id: 'h1', title: 'First half', children: ['q1', 'q2'] },
{ id: 'h2', title: 'Second half', children: ['q3', 'q4'] },
],
},
],
rows,
rowKey: 'id',
ariaLabel: 'Header group export',
};
let grouped = true;
let say: (message: LogText) => void = () => {};
/** Read the header rows and merge ranges from the first sheet of an uncompressed xlsx and show them as text. */
function describeSheet(bytes: Uint8Array): { head: string[]; merges: string[]; frozen: string } {
const text = new TextDecoder('utf-8').decode(bytes);
const xml = text.slice(text.search(/xl\/worksheets\/sheet1\.xml<\?xml/));
const frozen = /<pane [^>]*ySplit="(\d+)"/.exec(xml)?.[1] ?? '0';
const merges = [...xml.matchAll(/<mergeCell ref="([^"]+)"/g)].map((m) => m[1] as string);
const head: string[] = [];
for (let r = 1; r <= Number(frozen); r++) {
const line = new RegExp(`<row r="${r}"[^>]*>(.*?)</row>`).exec(xml)?.[1] ?? '';
const cells = [...line.matchAll(/<c r="([A-Z]+)\d+"[^>]*><is><t[^>]*>([^<]*)<\/t>/g)];
head.push(cells.map((c) => `${c[1]}${r}=${c[2]}`).join(' · '));
}
return { head, merges, frozen };
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
grouped = true;
withExport(api);
log(
'Press "Preview sheet" to log the header rows and merge ranges. Choose "Without groups" for the one-row header of 1.4.0.',
);
}
export const actions = {
mode: (_api: GridApi<Row>, v?: string) => void (grouped = v !== 'off'),
preview: (api: GridApi<Row>) => {
const bytes = withExport(api).exportXlsx({ headerGroups: grouped });
const { head, merges, frozen } = describeSheet(bytes);
say(`${frozen} header row(s) frozen · merges ${merges.join(', ') || 'none'}`);
head.forEach((line, i) => say(` row ${i + 1}: ${line}`));
},
download: async (api: GridApi<Row>) => {
await withExport(api).downloadXlsx('results-header-groups.xlsx', { headerGroups: grouped });
say('Downloaded.');
},
collapse: (api: GridApi<Row>) => {
api.setHeaderGroupState({ perf: { collapsed: true } });
say('Collapsed the "Results" group. The export follows the collapsed shape (no sub-groups).');
},
expand: (api: GridApi<Row>) => {
api.resetHeaderGroupState();
say('Expanded the "Results" group. The export includes the sub-groups.');
},
};