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.
코드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)
이 예제는 추가 패키지가 필요해요. 내 컴퓨터에서 돌리려면 npm i maxgrid @maxgrid/export로 설치하세요.
버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
<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>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));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.`,
});
},
}; 이 HTML은 추가 번들(위 script 태그)도 함께 불러오고 전역 변수로 써요. 별도 설치는 필요 없어요.
<!doctype html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>CSV 글자를 행으로 읽어 넣기</title>
</head>
<body>
<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>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.export.min.js"></script>
<script>
const { withExport } = MaxGridExport;
const rows = [{ id: 0, name: '(예전 행)', dept: 'dev', joined: null, active: false }];
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;
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;
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.`,
});
},
};
options.ariaLabel = "CSV 글자를 행으로 읽어 넣기";
const api = MaxGrid.createGrid(document.getElementById('grid'), options);
setup(api, (message) => {
const item = document.createElement('li');
item.textContent =
typeof message === 'string' ? message : navigator.language.startsWith('ko') ? message.ko : message.en;
document.getElementById('log').prepend(item);
});
document.getElementById('replace').addEventListener('click', () => actions.replace(api));
document.getElementById('append').addEventListener('click', () => actions.append(api));
document.getElementById('errors').addEventListener('click', () => actions.errors(api));
</script>
</body>
</html> 이 예제는 추가 패키지가 필요해요. 내 컴퓨터에서 돌리려면 npm i @maxgrid/react @maxgrid/export로 설치하세요.
버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
import { useEffect } from 'react';
import { Grid, useGridApi } from '@maxgrid/react';
import { actions, options, setup, type Row } from './example';
export function ExampleGrid() {
const [api, gridRef] = useGridApi<Row>();
useEffect(() => (api ? setup(api, console.log) : undefined), [api]);
return (
<>
<div className="toolbar">
<button
type="button"
disabled={!api}
onClick={() => api && actions.replace(api)}
>바꾸기</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.append(api)}
>뒤에 붙이기</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.errors(api)}
>잘못된 값</button>
</div>
<Grid style={{ height: 300 }} ref={gridRef} options={options} />
</>
);
}import { withExport, type ExportableGridApi } from '@maxgrid/export';
import type { GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
dept: string;
joined: string | null;
active: boolean;
}
const rows: Row[] = [{ id: 0, name: '(예전 행)', dept: 'dev', joined: null, active: false }];
export const options: GridOptions<Row> = {
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: (message: LogText) => void = () => {};
let ex: ExportableGridApi<Row> | undefined;
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
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: GridApi<Row>) => {
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: GridApi<Row>) => {
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.`,
});
},
}; 이 예제는 추가 패키지가 필요해요. 내 컴퓨터에서 돌리려면 npm i @maxgrid/vue @maxgrid/export로 설치하세요.
버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
<script setup lang="ts">
import { onBeforeUnmount, shallowRef } from 'vue';
import { Grid, type GridApi } from '@maxgrid/vue';
import { actions, options, setup, type Row } from './example';
const api = shallowRef<GridApi<Row> | null>(null);
let stop: (() => void) | undefined;
function onReady(event: { api: GridApi<Row> }) {
api.value = event.api;
stop = setup(event.api, console.log);
}
onBeforeUnmount(() => stop?.());
</script>
<template>
<div class="toolbar">
<button type="button" :disabled="!api" @click="api && actions.replace(api)">바꾸기</button>
<button type="button" :disabled="!api" @click="api && actions.append(api)">뒤에 붙이기</button>
<button type="button" :disabled="!api" @click="api && actions.errors(api)">잘못된 값</button>
</div>
<Grid style="height: 300px" :options="options" @ready="onReady" />
</template>import { withExport, type ExportableGridApi } from '@maxgrid/export';
import type { GridApi, GridOptions } from '@maxgrid/vue';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
dept: string;
joined: string | null;
active: boolean;
}
const rows: Row[] = [{ id: 0, name: '(예전 행)', dept: 'dev', joined: null, active: false }];
export const options: GridOptions<Row> = {
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: (message: LogText) => void = () => {};
let ex: ExportableGridApi<Row> | undefined;
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
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: GridApi<Row>) => {
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: GridApi<Row>) => {
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.`,
});
},
}; 이 예제는 추가 패키지가 필요해요. 내 컴퓨터에서 돌리려면 npm i @maxgrid/angular @maxgrid/export로 설치하세요.
버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
import { Component, OnDestroy } from '@angular/core';
import { GridComponent, isGridEvent, type GridApi, type GridEventMessage } from '@maxgrid/angular';
import { actions, options, setup, type Row } from './example';
@Component({
selector: 'app-example-grid',
standalone: true,
imports: [GridComponent],
template: `
<div class="toolbar">
<button
type="button"
[disabled]="!api"
(click)="api && actions.replace(api)"
>바꾸기</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.append(api)"
>뒤에 붙이기</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.errors(api)"
>잘못된 값</button>
</div>
<mx-grid style="height: 300px" [options]="options" [events]="relayed" (gridEvent)="onEvent($event)" />
`,
})
export class ExampleGridComponent implements OnDestroy {
readonly options = options;
readonly actions = actions;
readonly relayed = ['ready'] as const;
api: GridApi<Row> | null = null;
private stop: (() => void) | null = null;
onEvent(event: GridEventMessage<Row>): void {
if (isGridEvent(event, 'ready')) {
this.api = event.payload.api;
this.stop = setup(this.api, console.log);
}
}
ngOnDestroy(): void {
this.stop?.();
}
}import { withExport, type ExportableGridApi } from '@maxgrid/export';
import type { GridApi, GridOptions } from '@maxgrid/angular';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
dept: string;
joined: string | null;
active: boolean;
}
const rows: Row[] = [{ id: 0, name: '(예전 행)', dept: 'dev', joined: null, active: false }];
export const options: GridOptions<Row> = {
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: (message: LogText) => void = () => {};
let ex: ExportableGridApi<Row> | undefined;
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
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: GridApi<Row>) => {
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: GridApi<Row>) => {
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.`,
});
},
}; 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.
<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>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));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.`);
},
};This HTML also loads an extra bundle (the extra script tag above) and uses it as a global. No install is needed.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Read CSV text into rows</title>
</head>
<body>
<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>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.export.min.js"></script>
<script>
const { withExport } = MaxGridExport;
const rows = [{ id: 0, name: '(old row)', dept: 'dev', joined: null, active: false }];
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;
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;
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.`);
},
};
options.ariaLabel = "Read CSV text into rows";
const api = MaxGrid.createGrid(document.getElementById('grid'), options);
setup(api, (message) => {
const item = document.createElement('li');
item.textContent =
typeof message === 'string' ? message : navigator.language.startsWith('ko') ? message.ko : message.en;
document.getElementById('log').prepend(item);
});
document.getElementById('replace').addEventListener('click', () => actions.replace(api));
document.getElementById('append').addEventListener('click', () => actions.append(api));
document.getElementById('errors').addEventListener('click', () => actions.errors(api));
</script>
</body>
</html> This example needs an extra package. To run it locally, install with npm i @maxgrid/react @maxgrid/export.
When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
import { useEffect } from 'react';
import { Grid, useGridApi } from '@maxgrid/react';
import { actions, options, setup, type Row } from './example';
export function ExampleGrid() {
const [api, gridRef] = useGridApi<Row>();
useEffect(() => (api ? setup(api, console.log) : undefined), [api]);
return (
<>
<div className="toolbar">
<button
type="button"
disabled={!api}
onClick={() => api && actions.replace(api)}
>Replace</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.append(api)}
>Append</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.errors(api)}
>Bad values</button>
</div>
<Grid style={{ height: 300 }} ref={gridRef} options={options} />
</>
);
}import { withExport, type ExportableGridApi } from '@maxgrid/export';
import type { GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string;
export interface Row {
id: number;
name: string;
dept: string;
joined: string | null;
active: boolean;
}
const rows: Row[] = [{ id: 0, name: '(old row)', dept: 'dev', joined: null, active: false }];
export const options: GridOptions<Row> = {
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: (message: LogText) => void = () => {};
let ex: ExportableGridApi<Row> | undefined;
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
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: GridApi<Row>) => {
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: GridApi<Row>) => {
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.`,
);
},
}; This example needs an extra package. To run it locally, install with npm i @maxgrid/vue @maxgrid/export.
When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
<script setup lang="ts">
import { onBeforeUnmount, shallowRef } from 'vue';
import { Grid, type GridApi } from '@maxgrid/vue';
import { actions, options, setup, type Row } from './example';
const api = shallowRef<GridApi<Row> | null>(null);
let stop: (() => void) | undefined;
function onReady(event: { api: GridApi<Row> }) {
api.value = event.api;
stop = setup(event.api, console.log);
}
onBeforeUnmount(() => stop?.());
</script>
<template>
<div class="toolbar">
<button type="button" :disabled="!api" @click="api && actions.replace(api)">Replace</button>
<button type="button" :disabled="!api" @click="api && actions.append(api)">Append</button>
<button type="button" :disabled="!api" @click="api && actions.errors(api)">Bad values</button>
</div>
<Grid style="height: 300px" :options="options" @ready="onReady" />
</template>import { withExport, type ExportableGridApi } from '@maxgrid/export';
import type { GridApi, GridOptions } from '@maxgrid/vue';
export type LogText = string;
export interface Row {
id: number;
name: string;
dept: string;
joined: string | null;
active: boolean;
}
const rows: Row[] = [{ id: 0, name: '(old row)', dept: 'dev', joined: null, active: false }];
export const options: GridOptions<Row> = {
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: (message: LogText) => void = () => {};
let ex: ExportableGridApi<Row> | undefined;
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
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: GridApi<Row>) => {
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: GridApi<Row>) => {
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.`,
);
},
}; This example needs an extra package. To run it locally, install with npm i @maxgrid/angular @maxgrid/export.
When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
import { Component, OnDestroy } from '@angular/core';
import { GridComponent, isGridEvent, type GridApi, type GridEventMessage } from '@maxgrid/angular';
import { actions, options, setup, type Row } from './example';
@Component({
selector: 'app-example-grid',
standalone: true,
imports: [GridComponent],
template: `
<div class="toolbar">
<button
type="button"
[disabled]="!api"
(click)="api && actions.replace(api)"
>Replace</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.append(api)"
>Append</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.errors(api)"
>Bad values</button>
</div>
<mx-grid style="height: 300px" [options]="options" [events]="relayed" (gridEvent)="onEvent($event)" />
`,
})
export class ExampleGridComponent implements OnDestroy {
readonly options = options;
readonly actions = actions;
readonly relayed = ['ready'] as const;
api: GridApi<Row> | null = null;
private stop: (() => void) | null = null;
onEvent(event: GridEventMessage<Row>): void {
if (isGridEvent(event, 'ready')) {
this.api = event.payload.api;
this.stop = setup(this.api, console.log);
}
}
ngOnDestroy(): void {
this.stop?.();
}
}import { withExport, type ExportableGridApi } from '@maxgrid/export';
import type { GridApi, GridOptions } from '@maxgrid/angular';
export type LogText = string;
export interface Row {
id: number;
name: string;
dept: string;
joined: string | null;
active: boolean;
}
const rows: Row[] = [{ id: 0, name: '(old row)', dept: 'dev', joined: null, active: false }];
export const options: GridOptions<Row> = {
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: (message: LogText) => void = () => {};
let ex: ExportableGridApi<Row> | undefined;
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
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: GridApi<Row>) => {
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: GridApi<Row>) => {
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.`,
);
},
};