FreeGridv1.6.0English

내보내기와 가져오기

exportXlsx()는 행을 진짜 엑셀 파일로 저장합니다. 숫자는 컬럼 서식을 유지한 숫자로, 날짜는 날짜로 들어가며, 다단 헤더는 병합된 헤더 행이 되고, 머리글은 틀 고정과 필터 단추까지 붙습니다. exportCsv()는 BOM을 붙여 저장하므로 엑셀에서 열어도 한글이…

실행 예제내보내기·가져오기·필터 패널

엑셀·CSV·JSON·PDF로 저장하고, 엑셀·CSV 파일을 불러오고, 옆 패널에서 필터를 겁니다.

이 데모의 코드
import { createGrid, exportWorkbook, type ColumnDef } from '@freegridjs/core';
import { makeRows } from '../data';
import { button, separator, text, tr, type DemoContext } from '../ui';

export default function mount(ctx: DemoContext) {
  const { lang } = ctx;
  const h = (en: string, ko: string) => tr(lang, { en, ko });
  const columns: ColumnDef[] = [
    { field: 'id', header: 'ID', type: 'number', width: 80 },
    { field: 'name', header: h('Name', '이름'), width: 160, editable: true, align: 'center' },
    { field: 'country', header: h('Country', '국가'), width: 140, filter: 'set', editable: true },
    { header: h('Revenue', '매출'), children: [
      // low values are red; the color and the right alignment also go into the Excel file
      { field: 'q1', header: h('Q1', '1분기'), type: 'number', format: '#,##0', width: 110, editable: true,
        cellClass: ({ value }) => (Number(value) < 20000 ? 'demo-low' : undefined) },
      { field: 'q2', header: h('Q2', '2분기'), type: 'number', format: '#,##0', width: 110, editable: true },
    ] },
    { field: 'growth', header: h('Growth', '성장률'), type: 'number', format: '0.0%', width: 100 },
    { field: 'joined', header: h('Joined', '가입일'), type: 'date', width: 120, editable: true },
    { field: 'active', header: h('Active', '활성'), type: 'boolean', width: 80, editable: true },
  ];
  const grid = createGrid(ctx.host, {
    columns,
    data: makeRows(300),
    locale: lang,
    theme: 'classic',
    rowSelection: 'multiple',
    sideBar: { open: true, panels: ['filters', 'columns'] },
  });
  grid.on('filterChange', e => ctx.log(`filterChange → ${Object.keys(e.filters).join(', ') || h('none', '없음')}`));

  text(ctx, h('Filter on the right, then export only what you see. Right-click a cell for the same commands.',
    '오른쪽 필터 패널로 걸러 낸 뒤 보이는 행만 내보내 보세요. 셀을 우클릭해도 같은 메뉴가 나옵니다.'));
  separator(ctx);
  button(ctx, h('Export Excel', '엑셀로 내보내기'), () => grid.exportXlsx(h('freegrid-demo.xlsx', 'freegrid-데모.xlsx')));
  button(ctx, h('Export Excel without styles', '스타일 없이 엑셀로'), () => grid.exportXlsx('plain.xlsx', { styles: false }));
  button(ctx, h('Print', '인쇄'), () => grid.print({
    title: h('People', '사람 목록'),
    subtitle: h('Current sort and filters', '지금 정렬·필터 그대로'),
    footer: 'FreeGrid demo',
  }));
  // one file, two sheets: the filtered view and the checked rows
  button(ctx, h('Excel with two sheets', '시트 두 개짜리 엑셀'), () => exportWorkbook(h('two-sheets.xlsx', '시트2개.xlsx'), [
    { grid, sheetName: h('Filtered', '필터 결과') },
    { grid, sheetName: h('Checked', '체크한 행'), options: { rows: 'selected' } },
  ]));
  button(ctx, h('Export CSV', 'CSV로 내보내기'), () => grid.exportCsv(h('freegrid-demo.csv', 'freegrid-데모.csv')));
  button(ctx, h('Export checked rows', '체크한 행만 내보내기'), () => grid.exportXlsx('selected.xlsx', { rows: 'selected' }));
  separator(ctx);

  // Import: a hidden file input behind a normal button
  const input = document.createElement('input');
  input.type = 'file';
  input.accept = '.xlsx,.csv,.tsv,.txt';
  input.hidden = true;
  input.addEventListener('change', async () => {
    const file = input.files?.[0];
    input.value = '';
    if (!file) return;
    try {
      const res = await grid.importFile(file, { mode: 'append' });
      ctx.log(h(`imported ${res.rows.length} rows (${res.skipped} cells skipped) — Ctrl+Z undoes it`,
        `${res.rows.length}행을 가져왔습니다 (건너뛴 셀 ${res.skipped}개) — Ctrl+Z로 되돌릴 수 있습니다`));
      grid.scrollToRow(grid.getDisplayedRowCount() - 1);
    } catch (e) {
      ctx.log(`import failed: ${(e as Error).message}`);
    }
  });
  ctx.controls.append(input);
  button(ctx, h('Import Excel / CSV…', '엑셀·CSV 가져오기…'), () => input.click());
  return grid;
}

exportXlsx()는 행을 진짜 엑셀 파일로 저장합니다. 숫자는 컬럼 서식을 유지한 숫자로, 날짜는 날짜로 들어가며, 다단 헤더는 병합된 헤더 행이 되고, 머리글은 틀 고정과 필터 단추까지 붙습니다. exportCsv()는 BOM을 붙여 저장하므로 엑셀에서 열어도 한글이 깨지지 않습니다. 수식처럼 보이는 글자는 앞에 표시를 붙여 스프레드시트에서 실행되지 않게 합니다. 기본으로는 지금 보이는 정렬, 필터, 컬럼 그대로 내보내고, 옵션으로 다른 행이나 컬럼을 고를 수 있습니다.

importFile()은 .xlsx나 CSV 파일을 읽습니다. 첫 행을 헤더 이름이나 field 이름으로 컬럼에 맞추고, 값은 붙여넣기와 똑같이 검사합니다. 숫자 컬럼에는 숫자만, 날짜 컬럼에는 2026-03-05나 2026.3.5 같은 날짜만 들어갑니다. 가져온 행은 끝에 추가되며 실행 취소할 수 있고, 데이터를 통째로 바꿀 수도 있습니다. sideBar를 켜면 컬럼 패널 옆에 필터 패널이 생겨 여러 컬럼의 필터를 한곳에서 걸 수 있습니다.

엑셀 파일에는 컬럼의 align과 cellClass로 준 글자색·배경색·굵게가 함께 들어갑니다. 원하지 않으면 styles: false를 주세요.

// Download what people see (current sort and filters)
grid.exportXlsx('orders.xlsx');
grid.exportCsv('orders.csv', { separator: ';' });

// Pick columns and rows
grid.exportXlsx('picked.xlsx', { columns: ['name', 'total'], rows: 'selected', sheetName: 'Picked' });

// Read a file chosen by the user
input.addEventListener('change', async () => {
  const { rows, skipped } = await grid.importFile(input.files[0]);   // { mode: 'replace' } to swap
});

// Filters in a side panel next to the columns panel
createGrid(el, { columns, data, sideBar: { open: true, panels: ['filters', 'columns'] } });

// Without a grid
import { writeXlsx, readXlsx } from '@freegridjs/core';
const bytes = writeXlsx([{ name: 'Report', rows: [['Name', 'Total'], ['Kim', 1200]] }]);

JSON과 PDF

exportJson()은 행을 컬럼 id(또는 헤더)를 키로 한 객체 배열로 저장합니다. 숫자·참거짓·빈 값은 타입 그대로, 수식은 결과로 들어가고, formatted: true를 주면 화면에 보이는 글자 그대로 저장합니다. PDF는 인쇄와 PDF를 보세요. exportWorkbook()은 여러 그리드를 시트별로 한 엑셀 파일에 담습니다.

grid.exportJson('orders.json');                         // 지금 보이는 행과 컬럼
grid.exportJson('orders.json', { keys: 'header', rows: 'selected' });
const text = grid.getJson({ columns: ['id', 'amount'], space: 0 });   // [{"id":1,"amount":32000},…]
grid.exportPdf('orders.pdf', { title: '주문 목록' });

// 여러 그리드를 한 엑셀 파일에
exportWorkbook('report.xlsx', [{ grid: orders, sheetName: '주문' }, { grid: items, sheetName: '품목' }]);

이 페이지에 대한 질문

엑셀, CSV, JSON으로 내보낼 수 있나요?

네. exportXlsx는 서식·병합 헤더·색이 들어간 진짜 .xlsx를, exportCsv는 엑셀에서 한글이 깨지지 않는 CSV를, exportJson은 행 객체 배열을 저장합니다.

엑셀 파일을 그리드로 가져올 수 있나요?

네. importFile이 .xlsx와 CSV를 읽어 헤더나 field 이름으로 컬럼을 맞추고, 값은 붙여넣기와 똑같이 검사합니다.