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

CSV 글자를 행으로 읽어 넣기Read CSV text into rows

importCsv(text, options)는 CSV 글자를 행으로 읽어 돌려줘요. 첫 줄은 컬럼 이름(id·제목)이고, 값은 컬럼 종류에 맞게 바뀌어요(숫자, 날짜, 불리언, 선택 목록). 빈 줄은 건너뛰고 바꾸지 못한 칸은 null과 알림으로 알려요. 그리드에는 setRows·addRows로 직접 넣어요.importCsv(text, options) reads CSV text into rows and returns them. The first line holds the column names (id or title), and values are converted to the column kinds (number, date, boolean, select). Blank lines are skipped and cells that cannot be converted become null with a notice. You put the rows into the grid with setRows or addRows.

활용Intermediate
직접 써 보기Live previewCSV 글자를 행으로 읽어 넣기Read CSV text into rows

코드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">
    <button type="button" id="replace">바꾸기</button>
    <button type="button" id="append">뒤에 붙이기</button>
    <button type="button" id="errors">잘못된 값</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('replace').addEventListener('click', () => actions.replace(api));
document.getElementById('append').addEventListener('click', () => actions.append(api));
document.getElementById('errors').addEventListener('click', () => actions.errors(api));
example.js
import { withExport } from '@maxgrid/export';
const rows = [{ id: 0, name: '(예전 행)', dept: 'dev', joined: null, active: false }];
export const options = {
  columns: [
    { id: 'id', title: '번호', kind: 'number', width: 70 },
    { id: 'name', title: '이름', width: 150 },
    {
      id: 'dept',
      title: '부서',
      kind: 'select',
      width: 100,
      editorOptions: [
        { value: 'dev', label: '개발' },
        { value: 'ops', label: '운영' },
      ],
      optionLabel: (v) => (v === 'dev' ? '개발' : '운영'),
    },
    { id: 'joined', title: '입사일', kind: 'date', width: 110 },
    { id: 'active', title: '재직', kind: 'boolean', width: 70 },
  ],
  rows,
  rowKey: 'id',
};
const GOOD = '번호,이름,부서,입사일,재직\r\n11,"김하늘, 팀장",개발,2024.3.2,예\r\n12,이도윤,운영,2023/11/20,아니오\r\n\r\n13,박서연,개발,,yes\r\n';
const BAD = '번호,이름,부서,입사일,재직\r\n21,최지우,마케팅,2024-02-30,maybe\r\nabc,정민준,운영,2025-01-15,1\r\n';
let say = () => { };
let ex;
export function setup(api, log) {
  say = log;
  ex = withExport(api);
  log({
    ko: 'importCsv(text)는 CSV 글자를 행으로 읽어 돌려줘요. 그리드에는 setRows·addRows로 직접 넣어요.',
    en: 'importCsv(text) reads CSV text into rows and returns them. You put them into the grid yourself with setRows or addRows.',
  });
}
let appendCount = 0;
export const actions = {
  replace: (api) => {
    const result = ex?.importCsv(GOOD);
    if (!result)
      return;
    api.setRows(result.rows);
    say({
      ko: `${result.rows.length}행을 읽어 바꿨어요(건너뛴 빈 줄 ${result.skipped}, 알림 ${result.errors.length}). 날짜·불리언·부서가 컬럼 종류에 맞게 바뀌었어요.`,
      en: `Read and replaced ${result.rows.length} rows (${result.skipped} blank lines skipped, ${result.errors.length} notices). Dates, booleans and the department were converted to the column kinds.`,
    });
  },
  append: (api) => {
    const result = ex?.importCsv(GOOD);
    if (!result)
      return;
    const appended = (appendCount += 1) - 1;
    api.addRows(result.rows.map((r) => ({ ...r, id: r.id + 100 * (appended + 1) })));
    say({
      ko: `${result.rows.length}행을 뒤에 붙였어요(번호에 100씩 더해 겹치지 않게).`,
      en: `Appended ${result.rows.length} rows (ids shifted by 100 each time to avoid clashes).`,
    });
  },
  errors: () => {
    const result = ex?.importCsv(BAD);
    if (!result)
      return;
    for (const e of [...result.errors].reverse())
      say(`${e.line}: ${e.message}`);
    say({
      ko: `바꾸지 못한 칸 ${result.errors.length}개. 그 칸은 null이고 줄 번호와 이유가 알림으로 와요.`,
      en: `${result.errors.length} cells could not be converted. They become null and the line number and reason come back as notices.`,
    });
  },
};

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">
    <button type="button" id="replace">Replace</button>
    <button type="button" id="append">Append</button>
    <button type="button" id="errors">Bad values</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('replace').addEventListener('click', () => actions.replace(api));
document.getElementById('append').addEventListener('click', () => actions.append(api));
document.getElementById('errors').addEventListener('click', () => actions.errors(api));
example.js
import { withExport } from '@maxgrid/export';
const rows = [{ id: 0, name: '(old row)', dept: 'dev', joined: null, active: false }];
export const options = {
  columns: [
    { id: 'id', title: 'No.', kind: 'number', width: 70 },
    { id: 'name', title: 'Name', width: 150 },
    {
      id: 'dept',
      title: 'Department',
      kind: 'select',
      width: 120,
      editorOptions: [
        { value: 'dev', label: 'Dev' },
        { value: 'ops', label: 'Ops' },
      ],
      optionLabel: (v) => (v === 'dev' ? 'Dev' : 'Ops'),
    },
    { id: 'joined', title: 'Joined', kind: 'date', width: 110 },
    { id: 'active', title: 'Active', kind: 'boolean', width: 80 },
  ],
  rows,
  rowKey: 'id',
};
const GOOD = 'No.,Name,Department,Joined,Active\r\n11,"Carter, Liam (Lead)",Dev,2024.3.2,Yes\r\n12,Emma Stone,Ops,2023/11/20,No\r\n\r\n13,Noah Reed,Dev,,yes\r\n';
const BAD = 'No.,Name,Department,Joined,Active\r\n21,Olivia Hayes,Marketing,2024-02-30,maybe\r\nabc,Ethan Brooks,Ops,2025-01-15,1\r\n';
let say = () => { };
let ex;
export function setup(api, log) {
  say = log;
  ex = withExport(api);
  log('importCsv(text) reads CSV text into rows and returns them. You put them into the grid yourself with setRows or addRows.');
}
let appendCount = 0;
export const actions = {
  replace: (api) => {
    const result = ex?.importCsv(GOOD);
    if (!result)
      return;
    api.setRows(result.rows);
    say(`Read and replaced ${result.rows.length} rows (${result.skipped} blank lines skipped, ${result.errors.length} notices). Dates, booleans and the department were converted to the column kinds.`);
  },
  append: (api) => {
    const result = ex?.importCsv(GOOD);
    if (!result)
      return;
    const appended = (appendCount += 1) - 1;
    api.addRows(result.rows.map((r) => ({ ...r, id: r.id + 100 * (appended + 1) })));
    say(`Appended ${result.rows.length} rows (ids shifted by 100 each time to avoid clashes).`);
  },
  errors: () => {
    const result = ex?.importCsv(BAD);
    if (!result)
      return;
    for (const e of [...result.errors].reverse())
      say(`${e.line}: ${e.message}`);
    say(`${result.errors.length} cells could not be converted. They become null and the line number and reason come back as notices.`);
  },
};