플러그인 설명 / 내보내기 · 가져오기 · 인쇄개발 매뉴얼로 돌아가기

내보내기 · 가져오기 · 인쇄 플러그인

내보내기 · 가져오기 · 인쇄 · exportPlugin

CSV/XLSX 생성, CSV의 신규 행 가져오기, 현재 적재된 행의 인쇄 HTML을 제공합니다. 파일 형식별 범위와 데이터 기준을 구분해서 사용합니다.

설치 함수: exportPlugin() · 해제 이름: export

설정 속성 · 기본값

필수값은 해당 입력에서 반드시 제공하는 값입니다. 조건부 필수값은 설명에 적힌 기능을 사용할 때 필요합니다. 표시가 없는 옵션은 생략할 수 있으며 기본값을 사용합니다. 빈 문자열·누락과 0·false를 혼동하지 마세요.

설정 위치와 동작
설정기본값설명
함수 인수없음exportPlugin()으로 설치합니다.
exportCSV/exportXLSX의 downloadFilefalsetrue면 파일 다운로드를 시작합니다. false면 CSV 문자열 또는 XLSX Uint8Array를 반환합니다.
CSV 데이터현재 표시 컬럼·전체 적재 행필터로 화면에 줄어든 행만이 아니라 getRows()의 전체 적재 행을 사용합니다.
CSV 가져오기 값헤더 기준 매핑컬럼 title/field로 매핑하고 컬럼 parse·validate와 날짜 정규화를 적용합니다. 숫자·boolean 등은 parse를 직접 구성하세요. 신규 행 키만 추가합니다.

사용 순서

  1. exportPlugin()을 설치합니다.
  2. 파일이 필요하면 exportCSV/exportXLSX에 downloadFile:true를 전달합니다. 테스트나 전송용이면 반환값을 사용합니다.
  3. CSV 가져오기는 문자열을 importCSV에 전달하고, 인쇄는 print 또는 getPrintHTML을 사용합니다.

연결 API

플러그인 또는 연결된 Core API
호출동작
grid.exportCSV({downloadFile?})CSV 문자열 생성 및 선택적 다운로드. 수식으로 해석될 수 있는 값에는 보호 접두사를 사용합니다.
grid.exportXLSX({downloadFile?})XLSX 바이트 생성 및 선택적 다운로드. 단일 시트입니다.
grid.importCSV(text)신규 행을 추가하고 추가 행 수를 반환합니다. 중복 키·잘못된 CSV는 거부합니다.

필수값 grid.importCSV 인수: text

grid.getPrintHTML()현재 표시 컬럼·전체 적재 행의 인쇄 HTML을 반환합니다.
grid.print()새 인쇄 창을 열고 인쇄합니다. 팝업이 차단되면 오류를 냅니다.

설치 · 해제 · Vue 3 수명주기

생성 시 plugins에 등록하거나, 아직 설치하지 않은 인스턴스에서 grid.install을 호출합니다. 같은 name은 중복 설치할 수 없습니다. 설정에 쓰는 데이터·함수는 아래 전체 예제 소스를 참고하세요.

grid.install(exportPlugin());
grid.uninstall('export'); // 플러그인 해제
// Vue 3 컴포넌트가 종료될 때
onBeforeUnmount(() => grid.destroy());

해제 시 exportCSV/exportXLSX/importCSV/getPrintHTML/print 메서드를 제거합니다. 해제 후 이 메서드를 호출할 수 없습니다.

관련 이벤트

  • datachange (CSV 가져오기)

이벤트 구독은 grid.on(name, (detail, grid) => {})를 사용합니다. 해제 함수 또는 grid.off로 구독을 정리하세요.

실행 예제 · 실제 원본

아래 소스는 examples/features/export.js와 Vue 원본입니다. 해당 예제 경로를 기준으로 import하며, 행 데이터는 별도 파일을 함께 사용합니다.

JavaScript 전체 소스 · export.js
import { ZixoGrid, exportPlugin } from '../../src/index.js';
import { rows } from './export.data.js';
import { createToolbar } from '../feature-controls.js';
const host = document.querySelector('#grid'),
  toolbar = document.querySelector('#toolbar'),
  report = document.querySelector('#report');
const { button, select } = createToolbar(toolbar, report);
const options = {
  rowKey: 'id',
  height: 360,
  rows: rows,
  columns: [
    { field: 'name', title: '주문', width: 240 },
    { field: 'qty', title: '수량', type: 'number', parse: Number },
    { field: 'price', title: '단가', type: 'number', parse: Number },
  ],
  plugins: [exportPlugin()],
};

const grid = new ZixoGrid(host, options);

window.addEventListener('pagehide', () => grid.destroy(), { once: true });
grid.on(
  'validationerror',
  (detail) => (report.textContent = detail.error.message),
);
button('CSV 내보내기', () => grid.exportCSV({ downloadFile: true }));
button('XLSX 내보내기', () => grid.exportXLSX({ downloadFile: true }));
const upload = document.createElement('input');
upload.type = 'file';
upload.accept = '.csv';
upload.setAttribute('aria-label', 'CSV 가져오기');
upload.addEventListener('change', async () => {
  if (!upload.files[0]) return;
  try {
    report.textContent = grid.importCSV(await upload.files[0].text());
  } catch (e) {
    report.textContent = e.message;
  }
});
toolbar.append(upload);
report.textContent =
  'CSV 가져오기는 신규 키의 행을 추가합니다. XLSX Import는 지원하지 않습니다.';
Vue 3 전체 소스 · vue-export.vue
<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue';
import { ZixoGrid, exportPlugin } from '../../src/index.js';
import { rows } from './export.data.js';

// Instance and DOM belong to this component, never to window or a global ID.
const gridHost = ref(null);
const message = ref('');
const controls = ref([]);

let grid;
let alive = true;

async function run(action, value) {
  try {
    const result = await action(value);
    if (alive && result !== undefined)
      message.value =
        typeof result === 'string' ? result : JSON.stringify(result, null, 2);
  } catch (error) {
    if (alive) message.value = error.message;
  }
}

const button = (label, action) =>
  controls.value.push({ kind: 'button', label, action });

async function importFile(event) {
  const file = event.target.files?.[0];
  if (!file) return;
  const text = await file.text();
  if (alive) await run(() => grid.importCSV(text));
  event.target.value = '';
}
onMounted(() => {
  const options = {
    rowKey: 'id',
    height: 360,
    rows: rows,
    columns: [
      { field: 'name', title: '주문', width: 240 },
      { field: 'qty', title: '수량', type: 'number', parse: Number },
      { field: 'price', title: '단가', type: 'number', parse: Number },
    ],
    plugins: [exportPlugin()],
  };

  grid = new ZixoGrid(gridHost.value, options);

  grid.on(
    'validationerror',
    (detail) => (message.value = detail.error.message),
  );
  button('CSV 내보내기', () => grid.exportCSV({ downloadFile: true }));
  button('XLSX 내보내기', () => grid.exportXLSX({ downloadFile: true }));
  message.value =
    'CSV 가져오기는 신규 키의 행을 추가합니다. XLSX Import는 지원하지 않습니다.';
});
onBeforeUnmount(() => {
  alive = false;
  grid?.destroy(); // Cancels grid requests, removes events and releases plugins.
  grid = undefined;
});
defineExpose({ getGrid: () => grid });
</script>

<template>
  <main>
    <h1>CSV · XLSX · CSV Import</h1>
    <div class="toolbar">
      <template v-for="(control, index) in controls" :key="index">
        <button
          v-if="control.kind === 'button'"
          type="button"
          @click="run(control.action)"
        >
          {{ control.label }}
        </button>
        <label v-else
          >{{ control.label }}
          <select
            v-model="control.value"
            :aria-label="control.label"
            @change="run(control.action, control.value)"
          >
            <option v-for="value in control.values" :key="value" :value="value">
              {{ value }}
            </option>
          </select>
        </label>
      </template>
      <input
        type="file"
        accept=".csv"
        aria-label="CSV 가져오기"
        @change="importFile"
      />
    </div>
    <div ref="gridHost" class="vue-grid-host"></div>
    <div class="notes result" aria-live="polite">{{ message }}</div>
  </main>
</template>

제약 사항 · 주의할 동작

  • XLSX 가져오기·복수 시트·고급 셀 서식은 지원하지 않습니다.
  • CSV 가져오기는 ID 매칭 Update나 컬럼 매핑 UI를 제공하지 않습니다.
  • 서버의 아직 조회하지 않은 페이지는 내보내기/인쇄에 포함되지 않습니다.
  • 날짜 dateFormat과 셀 format은 화면 표시 설정입니다. 내보내기는 원시 데이터 값(날짜 ISO)을 사용합니다.

연결 기능 메뉴

CSV · XLSX · CSV Import · 적재된 전체 행 인쇄 · 서버 조회 · 저장 계약

이 플러그인 상세 페이지 독립 열기 ↗ · 플러그인 설명 전체