FreeGridv1.15.1English

CSV·JSON 내보내기와 가져오기

exportCsv와 exportJson으로 보이는 그대로 저장하고, importFile로 .xlsx와 CSV 파일을 붙여넣기처럼 검사하며 불러옵니다.

실행 예제CSV·JSON 내보내기와 가져오기

보이는 그대로 CSV나 JSON으로 저장하고, 엑셀·CSV 파일을 불러옵니다.

이 데모의 코드
import { createGrid, 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: [
      { field: 'q1', header: h('Q1', '1분기'), type: 'number', format: '#,##0', width: 110, editable: true },
      { 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',
    filterRow: true,
  });
  grid.on('filterChange', e => ctx.log(`filterChange → ${Object.keys(e.filters).join(', ') || h('none', '없음')}`));

  text(ctx, h('Filter with the boxes under the header, then export only what you see. Import an .xlsx or CSV file to add rows.',
    '헤더 아래 칸으로 걸러 낸 뒤 보이는 행만 내보내 보세요. .xlsx나 CSV 파일을 가져오면 행이 추가됩니다.'));
  separator(ctx);
  button(ctx, h('Export CSV', 'CSV로 내보내기'), () => grid.exportCsv(h('freegrid-demo.csv', 'freegrid-데모.csv')));
  button(ctx, h('Export JSON', 'JSON으로 내보내기'), () => grid.exportJson(h('freegrid-demo.json', 'freegrid-데모.json')));
  button(ctx, h('JSON as shown, by header', '화면 글자 그대로, 헤더를 키로'), () => {
    const json = grid.getJson({ keys: 'header', formatted: true, rows: 'filtered', space: 0 });
    ctx.log(json.slice(0, 160) + '…');
  });
  button(ctx, h('Checked rows as CSV', '체크한 행만 CSV로'), () => grid.exportCsv('selected.csv', { 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;
}

exportCsv()는 BOM을 붙인 CSV로 저장하므로 엑셀에서 열어도 한글이 깨지지 않습니다. 수식처럼 보이는 글자는 앞에 표시를 붙여 스프레드시트에서 실행되지 않게 합니다. exportJson()은 행을 컬럼 ID를 키로 한 객체 배열로 저장하고, keys: 'header'를 주면 헤더를 키로 씁니다. 숫자·참거짓·빈 값은 타입 그대로, 계산 컬럼은 결과로 들어가고, formatted: true를 주면 화면에 보이는 글자 그대로 저장합니다.

둘 다 기본으로 지금 보이는 정렬, 필터, 컬럼 그대로, 행은 그리드에 나오는 순서(그룹별로, 부모 다음 자식, 접힌 행 포함)로 내보냅니다. rows: 'all'은 원본 순서의 모든 행을, rows: 'selected'는 필터를 통과한 체크한 행을 같은 순서로 내보내고, columns로 숨긴 컬럼까지 포함해 컬럼을 고를 수 있습니다. 파일로 받지 않고 글자로 받으려면 getCsv()와 getJson()을 쓰고, CSV 구분자는 separator로 ; 등으로 바꿀 수 있습니다.

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

// Pick columns and rows
grid.exportCsv('picked.csv', { columns: ['name', 'total'], rows: 'selected' });
grid.exportJson('orders.json', { keys: 'header', formatted: true });
const text = grid.getJson({ columns: ['id', 'amount'], space: 0 });   // [{"id":1,"amount":32000},…]

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

// Without a grid
import { parseCsv, readXlsx } from '@freegridjs/core';
const lines = parseCsv('name;total
Kim;1200');          // the separator is detected
const sheets = readXlsx(new Uint8Array(await file.arrayBuffer()));

엑셀·CSV 파일 가져오기

importFile()은 .xlsx나 CSV 파일을 읽습니다. 첫 행을 헤더 이름이나 field 이름으로 컬럼에 맞추고, 값은 붙여넣기와 똑같이 검사합니다. 숫자 컬럼에는 숫자만, 날짜 컬럼에는 2026-03-05나 2026.3.5 같은 날짜만 들어갑니다. 가져온 행은 끝에 추가되며 Ctrl+Z로 되돌릴 수 있고, mode: 'replace'를 주면 데이터를 통째로 바꿉니다. 시트는 sheet로 고릅니다. 결과에는 들어온 행 수와 건너뛴 셀 수가 담깁니다. 그리드 없이 같은 파일을 배열로 읽으려면 readXlsx()와 parseCsv()를 쓰세요.

서식과 색이 살아 있는 엑셀 파일, 여러 그리드를 담은 통합 문서, PDF 파일은 엑셀·PDF 내보내기를, 인쇄는 인쇄를 보세요.

이 페이지에 대한 질문

CSV와 JSON으로 내보낼 수 있나요?

네. exportCsv는 엑셀에서 한글이 깨지지 않도록 BOM을 붙인 CSV를, exportJson은 행 객체 배열을 저장합니다. 둘 다 지금 정렬과 필터를 따릅니다.

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

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