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

머리글 그룹을 엑셀에 병합 셀로 내보내기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.

활용Intermediate
직접 써 보기Live preview머리글 그룹을 엑셀에 병합 셀로 내보내기Export header groups to Excel as merged cells

코드Code

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

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

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

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

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

index.html
<div id="app">
  <div class="toolbar">
    <select aria-label="내보내기 모양" id="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>
main.js
import { createGrid } from 'maxgrid';
import { actions, options, setup } from './example';
const api = createGrid(document.getElementById('grid'), options);
setup(api, console.log);
document.getElementById('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));
example.js
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.',
    });
  },
};

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

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

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

index.html
<div id="app">
  <div class="toolbar">
    <select aria-label="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>
main.js
import { createGrid } from 'maxgrid';
import { actions, options, setup } from './example';
const api = createGrid(document.getElementById('grid'), options);
setup(api, console.log);
document.getElementById('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));
example.js
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.');
  },
};