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

끌어다 놓은 파일을 뒤에 붙이고 거르기Append dropped files and filter them

mode: 'append', accept, maxSize, columns, beforeFileImport로 받을 파일과 붙이는 방법을 정해요.Use mode: 'append', accept, maxSize, columns and beforeFileImport to decide which files are taken and how they are added.

활용Intermediate
직접 써 보기Live preview끌어다 놓은 파일을 뒤에 붙이고 거르기Append dropped files and filter them

코드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="csv">CSV 받기</button>
    <button type="button" id="xlsx">xlsx 받기</button>
    <button type="button" id="skip">건너뛸 파일</button>
    <button type="button" id="bad">받지 않는 형식</button>
    <button type="button" id="choose">파일 고르기</button>
  </div>
  <div id="grid" style="height: 340px"></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('csv').addEventListener('click', () => actions.csv(api));
document.getElementById('xlsx').addEventListener('click', () => actions.xlsx(api));
document.getElementById('skip').addEventListener('click', () => actions.skip(api));
document.getElementById('bad').addEventListener('click', () => actions.bad(api));
document.getElementById('choose').addEventListener('click', () => actions.choose(api));
example.js
import { exportXlsx, withExport } from '@maxgrid/export';
let say = () => { };
// mode: 'append'는 가져온 행을 뒤에 붙여요. accept로 받을 형식을, maxSize로 크기 상한(바이트)을, columns로 머리글 → 컬럼 id를 정해요.
// beforeFileImport는 false를 돌려주면 그 파일을 가져오지 않아요(여기서는 이름이 "skip"으로 시작하는 파일).
export const options = {
  columns: [
    { id: 'id', title: '번호', kind: 'number', width: 70 },
    { id: 'name', title: '이름', width: 140 },
    { id: 'team', title: '팀', width: 100 },
    { id: 'pay', title: '급여', kind: 'number', width: 100 },
  ],
  rows: [{ id: 1, name: '김하늘', team: '개발', pay: 3200 }],
  rowKey: 'id',
  fileDrop: {
    mode: 'append',
    accept: ['csv', 'xlsx'],
    maxSize: 100 * 1024,
    columns: { 사번: 'id', 직원: 'name', 소속: 'team', 급여액: 'pay' },
  },
  hooks: {
    beforeFileImport: ({ file }) => {
      if (file.name.startsWith('skip')) {
        say({ ko: `${file.name}: 가져오기를 취소했어요.`, en: `${file.name}: import cancelled.` });
        return false;
      }
    },
  },
};
let batch = 0;
const NAMES = ['이도윤', '박서연', '최지우'];
const TEAMS = ['운영', '디자인', '개발'];
// 내려받을 때마다 사번이 겹치지 않게 100씩 올려요.
const sample = () => NAMES.map((n, i) => ({
  id: batch * 100 + i + 2,
  name: n,
  team: TEAMS[i],
  pay: 3300 + i * 250,
}));
function save(name, data, type) {
  const a = document.createElement('a');
  a.href = URL.createObjectURL(new Blob([data], { type }));
  a.download = name;
  a.click();
  setTimeout(() => URL.revokeObjectURL(a.href), 1000);
}
export function setup(api, log) {
  say = log;
  withExport(api);
  api.on('fileImported', (e) => log({
    ko: `${e.name}: ${e.rowCount}행을 뒤에 붙였어요.`,
    en: `${e.name}: appended ${e.rowCount} rows.`,
  }));
  api.on('error', (e) => log({ ko: `오류: ${e.message}`, en: `Error: ${e.message}` }));
  log({
    ko: '내려받은 파일을 끌어다 놓으면 행이 뒤에 붙어요. 머리글이 "사번·직원…"이라 columns 옵션으로 이어 줘요. csv·xlsx만 받고 100KB를 넘으면 거절해요.',
    en: 'Drop the downloaded file and the rows are appended. The headers are "사번, 직원…", linked by the columns option. Only csv and xlsx are accepted, and files over 100 KB are refused.',
  });
}
export const actions = {
  csv: () => {
    batch += 1;
    const rows = sample();
    save('team.csv', `사번,직원,소속,급여액\r\n${rows.map((r) => `${r.id},${r.name},${r.team},${r.pay}`).join('\r\n')}\r\n`, 'text/csv');
  },
  xlsx: () => {
    batch += 1;
    save('team.xlsx', exportXlsx({
      columns: [
        { id: 'id', title: '사번', kind: 'number' },
        { id: 'name', title: '직원' },
        { id: 'team', title: '소속' },
        { id: 'pay', title: '급여액', kind: 'number' },
      ],
      rows: sample(),
    }), 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  },
  skip: () => save('skip-me.csv', '사번,직원\r\n999,건너뛸 사람\r\n', 'text/csv'),
  bad: () => save('notes.txt', '이 형식은 받지 않아요', 'text/plain'),
  choose: (api) => api.openFileDialog(),
};

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="csv">CSV</button>
    <button type="button" id="xlsx">xlsx</button>
    <button type="button" id="skip">File to skip</button>
    <button type="button" id="bad">Unsupported format</button>
    <button type="button" id="choose">Choose a file</button>
  </div>
  <div id="grid" style="height: 340px"></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('csv').addEventListener('click', () => actions.csv(api));
document.getElementById('xlsx').addEventListener('click', () => actions.xlsx(api));
document.getElementById('skip').addEventListener('click', () => actions.skip(api));
document.getElementById('bad').addEventListener('click', () => actions.bad(api));
document.getElementById('choose').addEventListener('click', () => actions.choose(api));
example.js
import { exportXlsx, withExport } from '@maxgrid/export';
let say = () => { };
// mode: 'append' appends the imported rows. accept sets the formats, maxSize the size limit (bytes), columns header text to column id.
// Returning false from beforeFileImport skips that file (here: files whose name starts with "skip").
export const options = {
  columns: [
    { id: 'id', title: 'No.', kind: 'number', width: 70 },
    { id: 'name', title: 'Name', width: 140 },
    { id: 'team', title: 'Team', width: 100 },
    { id: 'pay', title: 'Pay', kind: 'number', width: 100 },
  ],
  rows: [{ id: 1, name: 'Liam Carter', team: 'Dev', pay: 3200 }],
  rowKey: 'id',
  fileDrop: {
    mode: 'append',
    accept: ['csv', 'xlsx'],
    maxSize: 100 * 1024,
    columns: { 'Staff ID': 'id', Employee: 'name', Group: 'team', 'Pay amount': 'pay' },
  },
  hooks: {
    beforeFileImport: ({ file }) => {
      if (file.name.startsWith('skip')) {
        say(`${file.name}: import cancelled.`);
        return false;
      }
    },
  },
};
let batch = 0;
const NAMES = ['Emma Stone', 'Noah Reed', 'Ava Brooks'];
const TEAMS = ['Ops', 'Design', 'Dev'];
// Each download adds 100 to the ids so they never clash.
const sample = () => NAMES.map((n, i) => ({
  id: batch * 100 + i + 2,
  name: n,
  team: TEAMS[i],
  pay: 3300 + i * 250,
}));
function save(name, data, type) {
  const a = document.createElement('a');
  a.href = URL.createObjectURL(new Blob([data], { type }));
  a.download = name;
  a.click();
  setTimeout(() => URL.revokeObjectURL(a.href), 1000);
}
export function setup(api, log) {
  say = log;
  withExport(api);
  api.on('fileImported', (e) => log(`${e.name}: appended ${e.rowCount} rows.`));
  api.on('error', (e) => log(`Error: ${e.message}`));
  log('Drop the downloaded file and the rows are appended. The headers are "Staff ID, Employee...", linked by the columns option. Only csv and xlsx are accepted, and files over 100 KB are refused.');
}
export const actions = {
  csv: () => {
    batch += 1;
    const rows = sample();
    save('team.csv', `Staff ID,Employee,Group,Pay amount\r\n${rows.map((r) => `${r.id},${r.name},${r.team},${r.pay}`).join('\r\n')}\r\n`, 'text/csv');
  },
  xlsx: () => {
    batch += 1;
    save('team.xlsx', exportXlsx({
      columns: [
        { id: 'id', title: 'Staff ID', kind: 'number' },
        { id: 'name', title: 'Employee' },
        { id: 'team', title: 'Group' },
        { id: 'pay', title: 'Pay amount', kind: 'number' },
      ],
      rows: sample(),
    }), 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  },
  skip: () => save('skip-me.csv', 'Staff ID,Employee\r\n999,Skipped person\r\n', 'text/csv'),
  bad: () => save('notes.txt', 'This format is not accepted', 'text/plain'),
  choose: (api) => api.openFileDialog(),
};