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

엑셀 숫자 서식(천 단위·통화·퍼센트) 입히기Excel number formats: thousands, currency, percent

단가·마진율·재고를 글자가 아닌 숫자 값으로 내려받고, 엑셀 서식 코드로 천 단위 쉼표·원·퍼센트를 보여 줘요.Download price, margin and stock as real numbers and let Excel format codes show thousands separators, currency and percent.

활용Intermediate
직접 써 보기Live preview엑셀 숫자 서식(천 단위·통화·퍼센트) 입히기Excel number formats: thousands, currency, percent

코드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="excel" selected>엑셀 서식</option>
      <option value="plain">서식 없음</option>
    </select>
    <button type="button" id="download">엑셀로 내려받기</button>
  </div>
  <div id="grid" style="height: 330px"></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('download').addEventListener('click', () => actions.download(api));
example.js
import { withExport } from '@maxgrid/export';
const items = ['볼트 M8', '너트 M8', '와셔 8mm', '앵커 10mm', '렌치 세트', '장갑 L'];
const rows = items.map((item, i) => ({
  id: i + 1,
  item,
  price: 1200 + i * 3450,
  rate: 0.035 + i * 0.0125,
  stock: 40 + i * 117,
}));
// 화면에는 글자(1,200원, 3.5%)로 보여 주지만, 엑셀 파일에는 숫자 값을 넣고 서식만 입혀요.
export const options = {
  columns: [
    { id: 'item', title: '품목', width: 120 },
    {
      id: 'price',
      title: '단가',
      kind: 'number',
      width: 100,
      align: 'end',
      formatValue: (v) => `${Number(v).toLocaleString('ko-KR')}원`,
    },
    {
      id: 'rate',
      title: '마진율',
      kind: 'number',
      width: 90,
      align: 'end',
      formatValue: (v) => `${(Number(v) * 100).toFixed(1)}%`,
    },
    { id: 'stock', title: '재고', kind: 'number', width: 80, align: 'end' },
  ],
  rows,
  rowKey: 'id',
};
const FORMATS = {
  excel: { price: '#,##0"원"', rate: '0.0%', stock: '#,##0' },
  plain: undefined,
};
let mode = 'excel';
// 만든 파일의 셀이 숫자인지 글자인지 파일 안(XML)에서 읽어 기록 줄에 보여 줘요.
function describeCell(book, ref, title) {
  const cell = new RegExp(`<c r="${ref}"[^>]*>(.*?)</c>`).exec(book)?.[1] ?? '';
  const text = /<t[^>]*>([^<]*)<\/t>/.exec(cell)?.[1];
  const number = /<v>([^<]*)<\/v>/.exec(cell)?.[1];
  if (text !== undefined)
    return { ko: `${ref} ${title.ko}: 글자 "${text}"`, en: `${ref} ${title.en}: text "${text}"` };
  return {
    ko: `${ref} ${title.ko}: 숫자 ${number ?? '(비어 있음)'}`,
    en: `${ref} ${title.en}: number ${number ?? '(empty)'}`,
  };
}
export const actions = {
  mode: (_api, v) => void (mode = v === 'plain' ? 'plain' : 'excel'),
  download: async (api) => {
    const numberFormats = FORMATS[mode];
    const options = { sheetName: '품목', ...(numberFormats ? { numberFormats } : {}) };
    const ex = withExport(api);
    await ex.downloadXlsx('품목-숫자서식.xlsx', options);
    // 동기 xlsx는 압축하지 않아서 바이트를 글자로 바꾸면 안의 XML이 그대로 보여요.
    const book = new TextDecoder('utf-8').decode(ex.exportXlsx(options));
    // 기록 줄은 새 글이 위에 쌓여요. 아래에서 위로 읽히도록 셀 줄을 먼저, 요약을 마지막에 적어요.
    say(describeCell(book, 'D2', { ko: '재고', en: 'Stock' }));
    say(describeCell(book, 'C2', { ko: '마진율', en: 'Margin' }));
    say(describeCell(book, 'B2', { ko: '단가', en: 'Unit price' }));
    say(mode === 'excel'
      ? {
        ko: '내려받았어요. 셀은 숫자이고, 엑셀이 서식으로 보여 줘요.',
        en: 'Downloaded. The cells are numbers and Excel shows them with a format.',
      }
      : {
        ko: '내려받았어요. 서식 없이 화면 글자가 그대로 들어 있어 엑셀에서 합계를 낼 수 없어요.',
        en: 'Downloaded. The cells hold the on-screen text without a format, so Excel cannot sum them.',
      });
  },
};
let say = () => { };
export function setup(api, log) {
  say = log;
  withExport(api);
  log({ ko: '숫자 서식을 입혀 내려받아요.', en: 'Downloads with number formats applied.' });
}

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="Number format" id="mode">
      <option value="excel" selected>Excel formats</option>
      <option value="plain">No format</option>
    </select>
    <button type="button" id="download">Download xlsx</button>
  </div>
  <div id="grid" style="height: 330px"></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('download').addEventListener('click', () => actions.download(api));
example.js
import { withExport } from '@maxgrid/export';
const items = ['Bolt M8', 'Nut M8', 'Washer 8mm', 'Anchor 10mm', 'Wrench set', 'Gloves L'];
const rows = items.map((item, i) => ({
  id: i + 1,
  item,
  price: 1200 + i * 3450,
  rate: 0.035 + i * 0.0125,
  stock: 40 + i * 117,
}));
// The screen shows text ($1,200, 3.5%), but the Excel file holds number values with only a format applied.
export const options = {
  columns: [
    { id: 'item', title: 'Item', width: 130 },
    {
      id: 'price',
      title: 'Price',
      kind: 'number',
      width: 100,
      align: 'end',
      formatValue: (v) => `$${Number(v).toLocaleString('en-US')}`,
    },
    {
      id: 'rate',
      title: 'Margin',
      kind: 'number',
      width: 90,
      align: 'end',
      formatValue: (v) => `${(Number(v) * 100).toFixed(1)}%`,
    },
    { id: 'stock', title: 'Stock', kind: 'number', width: 80, align: 'end' },
  ],
  rows,
  rowKey: 'id',
};
const FORMATS = {
  excel: { price: '"$"#,##0', rate: '0.0%', stock: '#,##0' },
  plain: undefined,
};
let mode = 'excel';
// Read from the XML inside the built file whether a cell is a number or text, and show it as a log line.
function describeCell(book, ref, title) {
  const cell = new RegExp(`<c r="${ref}"[^>]*>(.*?)</c>`).exec(book)?.[1] ?? '';
  const text = /<t[^>]*>([^<]*)<\/t>/.exec(cell)?.[1];
  const number = /<v>([^<]*)<\/v>/.exec(cell)?.[1];
  if (text !== undefined)
    return `${ref} ${title}: text "${text}"`;
  return `${ref} ${title}: number ${number ?? '(empty)'}`;
}
export const actions = {
  mode: (_api, v) => void (mode = v === 'plain' ? 'plain' : 'excel'),
  download: async (api) => {
    const numberFormats = FORMATS[mode];
    const options = { sheetName: 'Items', ...(numberFormats ? { numberFormats } : {}) };
    const ex = withExport(api);
    await ex.downloadXlsx('items-number-format.xlsx', options);
    // The synchronous xlsx is not compressed, so turning the bytes into text shows the XML inside.
    const book = new TextDecoder('utf-8').decode(ex.exportXlsx(options));
    // The log stacks new lines on top. To read bottom to top, write the cell lines first and the summary last.
    say(describeCell(book, 'D2', 'Stock'));
    say(describeCell(book, 'C2', 'Margin'));
    say(describeCell(book, 'B2', 'Price'));
    say(mode === 'excel'
      ? 'Downloaded. The cells are numbers and Excel shows them with a format.'
      : 'Downloaded. The cells hold the on-screen text without a format, so Excel cannot sum them.');
  },
};
let say = () => { };
export function setup(api, log) {
  say = log;
  withExport(api);
  log('Downloads with number formats applied.');
}