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

엑셀 파일에 시트 여러 개 넣기Several sheets in one xlsx file

화면의 주문 표와 지역별 합계 표를 한 엑셀 파일의 두 시트로 내려받아요.Download the orders grid and a per-region totals table as two sheets of one xlsx file.

활용Intermediate
직접 써 보기Live preview엑셀 파일에 시트 여러 개 넣기Several sheets in one xlsx file

코드Code

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

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

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

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

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

index.html
<div id="app">
  <div class="toolbar">
    <select aria-label="합계 시트" id="totals">
      <option value="yes" selected>넣음</option>
      <option value="no">뺌</option>
    </select>
    <select aria-label="둘째 시트 이름" id="name">
      <option value="ok" selected>지역별 합계</option>
      <option value="clash">겹치는 이름(오류 보기)</option>
    </select>
    <button type="button" id="download">엑셀로 내려받기</button>
  </div>
  <div id="grid" style="height: 370px"></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('totals').addEventListener('change', (event) => actions.totals(api, event.target.value));
document.getElementById('name').addEventListener('change', (event) => actions.name(api, event.target.value));
document.getElementById('download').addEventListener('click', () => actions.download(api));
example.js
import { withExport, xlsxSheet } from '@maxgrid/export';
const customers = ['한빛푸드', '소나무철물', '파란마켓', '단풍상회'];
const regions = ['서울', '부산', '대전', '광주'];
const rows = Array.from({ length: 10 }, (_, i) => ({
  id: i + 1,
  orderNo: `SO-${3001 + i}`,
  customer: customers[i % customers.length],
  region: regions[i % regions.length],
  qty: 3 + ((i * 7) % 28),
  orderedAt: new Date(2026, 9, 1 + i * 2),
}));
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: 'orderedAt', title: '주문일', kind: 'date', width: 110 },
  ],
  rows,
  rowKey: 'id',
};
function totals() {
  const byRegion = new Map();
  for (const r of rows) {
    const t = byRegion.get(r.region) ?? { region: r.region, orders: 0, qty: 0 };
    t.orders += 1;
    t.qty += r.qty;
    byRegion.set(r.region, t);
  }
  return [...byRegion.values()];
}
let withTotals = true;
// '겹치는 이름'을 고르면 둘째 시트 이름이 첫 시트("주문")와 같아져서 오류를 볼 수 있어요.
let clash = false;
const FIRST_SHEET = '주문';
const totalSheet = () => xlsxSheet(clash ? FIRST_SHEET : '지역별 합계', {
  columns: [
    { id: 'region', title: '지역' },
    { id: 'orders', title: '주문 수', kind: 'number' },
    { id: 'qty', title: '수량 합계', kind: 'number' },
  ],
  rows: totals(),
});
// 내려받는 동안에는 버튼을 흐리게 해서 같은 파일이 두 번 저장되지 않게 해요.
function setBusy(busy) {
  const button = document.getElementById('download');
  if (button instanceof HTMLButtonElement)
    button.disabled = busy;
}
export const actions = {
  totals: (_api, v) => void (withTotals = v !== 'no'),
  name: (_api, v) => void (clash = v === 'clash'),
  download: async (api) => {
    const sheets = withTotals ? [totalSheet()] : [];
    setBusy(true);
    try {
      await withExport(api).downloadXlsx('주문-여러시트.xlsx', { sheetName: FIRST_SHEET, sheets });
      say({
        ko: `내려받았어요. 시트 ${sheets.length + 1}개: 주문${withTotals ? ', 지역별 합계' : ''}`,
        en: `Downloaded. ${sheets.length + 1} sheets: 주문${withTotals ? ', 지역별 합계' : ''}`,
      });
    }
    catch (error) {
      // 시트 이름이 겹치면 파일을 만들기 전에 오류가 나서, 아무것도 저장되지 않아요.
      say({
        ko: `내려받지 못했어요: ${error instanceof Error ? error.message : String(error)}`,
        en: `Could not download: ${error instanceof Error ? error.message : String(error)}`,
      });
    }
    finally {
      setBusy(false);
    }
  },
};
let say = () => { };
export function setup(api, log) {
  say = log;
  withExport(api);
  log({
    ko: '"주문"과 "지역별 합계" 두 시트로 내려받아요.',
    en: 'Downloads two sheets, "주문" (orders) and "지역별 합계" (totals by region).',
  });
}

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="Totals sheet" id="totals">
      <option value="yes" selected>Include</option>
      <option value="no">Leave out</option>
    </select>
    <select aria-label="Second sheet name" id="name">
      <option value="ok" selected>Region totals</option>
      <option value="clash">Clashing name (see the error)</option>
    </select>
    <button type="button" id="download">Download xlsx</button>
  </div>
  <div id="grid" style="height: 370px"></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('totals').addEventListener('change', (event) => actions.totals(api, event.target.value));
document.getElementById('name').addEventListener('change', (event) => actions.name(api, event.target.value));
document.getElementById('download').addEventListener('click', () => actions.download(api));
example.js
import { withExport, xlsxSheet } from '@maxgrid/export';
const customers = ['Harbor Foods', 'Pine Hardware', 'Blue Market', 'Maple Trading'];
const regions = ['Seoul', 'Busan', 'Daejeon', 'Gwangju'];
const rows = Array.from({ length: 10 }, (_, i) => ({
  id: i + 1,
  orderNo: `SO-${3001 + i}`,
  customer: customers[i % customers.length],
  region: regions[i % regions.length],
  qty: 3 + ((i * 7) % 28),
  orderedAt: new Date(2026, 9, 1 + i * 2),
}));
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: 'orderedAt', title: 'Ordered', kind: 'date', width: 110 },
  ],
  rows,
  rowKey: 'id',
};
function totals() {
  const byRegion = new Map();
  for (const r of rows) {
    const t = byRegion.get(r.region) ?? { region: r.region, orders: 0, qty: 0 };
    t.orders += 1;
    t.qty += r.qty;
    byRegion.set(r.region, t);
  }
  return [...byRegion.values()];
}
let withTotals = true;
// Choosing "clash" makes the second sheet name equal to the first sheet ("Orders"), so you can see the error.
let clash = false;
const FIRST_SHEET = 'Orders';
const totalSheet = () => xlsxSheet(clash ? FIRST_SHEET : 'Totals by region', {
  columns: [
    { id: 'region', title: 'Region' },
    { id: 'orders', title: 'Orders', kind: 'number' },
    { id: 'qty', title: 'Total qty', kind: 'number' },
  ],
  rows: totals(),
});
// Dim the button while downloading so the same file is not saved twice.
function setBusy(busy) {
  const button = document.getElementById('download');
  if (button instanceof HTMLButtonElement)
    button.disabled = busy;
}
export const actions = {
  totals: (_api, v) => void (withTotals = v !== 'no'),
  name: (_api, v) => void (clash = v === 'clash'),
  download: async (api) => {
    const sheets = withTotals ? [totalSheet()] : [];
    setBusy(true);
    try {
      await withExport(api).downloadXlsx('orders-multi-sheet.xlsx', {
        sheetName: FIRST_SHEET,
        sheets,
      });
      say(`Downloaded. ${sheets.length + 1} sheets: Orders${withTotals ? ', Totals by region' : ''}`);
    }
    catch (error) {
      // If sheet names clash, the error happens before the file is built, so nothing is saved.
      say(`Could not download: ${error instanceof Error ? error.message : String(error)}`);
    }
    finally {
      setBusy(false);
    }
  },
};
let say = () => { };
export function setup(api, log) {
  say = log;
  withExport(api);
  log('Downloads two sheets, "Orders" and "Totals by region".');
}