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

고른 칸을 엑셀로 복사하고 붙여넣기Copy selected cells to Excel and paste back

고른 칸을 탭과 줄바꿈으로 이은 글자로 복사하면 엑셀에 그대로 붙여넣을 수 있어요. 반대로 그런 글자를 표에 붙이면 고른 칸부터 채우고, 값이 안 맞는 칸은 건너뛰며 몇 칸이 바뀌었는지 알려 줘요.Copying selected cells gives tab and newline separated text that pastes straight into Excel. Pasting such text back fills from the selected cell, skips cells whose value does not fit and reports how many changed.

활용Intermediate
직접 써 보기Live preview고른 칸을 엑셀로 복사하고 붙여넣기Copy selected cells to Excel and paste back

코드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 탭이나 직접 해보기를 쓰세요.

버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.

index.html
<div id="app">
  <div class="toolbar">
    <select aria-label="머리글" id="header">
      <option value="none" selected>값만 (기본)</option>
      <option value="columns">머리글 포함</option>
    </select>
    <button type="button" id="copy">선택한 칸 복사</button>
    <button type="button" id="pasteSample">붙여넣기 시험</button>
  </div>
  <div id="grid" style="height: 330px"></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('header').addEventListener('change', (event) => actions.header(api, event.target.value));
document.getElementById('copy').addEventListener('click', () => actions.copy(api));
document.getElementById('pasteSample').addEventListener('click', () => actions.pasteSample(api));
example.js
const menus = ['아메리카노', '카페라떼', '바닐라라떼', '콜드브루', '카푸치노', '녹차라떼'];
export const options = {
  columns: [
    { id: 'menu', title: '메뉴', width: 140, editable: true },
    { id: 'qty', title: '수량', kind: 'number', width: 90, editable: true },
    {
      id: 'price',
      title: '단가',
      kind: 'number',
      width: 110,
      editable: true,
      formatValue: (value) => Number(value).toLocaleString('ko-KR'),
    },
  ],
  rows: menus.map((menu, i) => ({
    id: i + 1,
    menu,
    qty: 3 + ((i * 7) % 9),
    price: 4000 + i * 300,
  })),
  rowKey: 'id',
  cellSelection: 'multiple',
};
let say = () => { };
let header = 'none';
// 탭·줄바꿈이 눈에 보이도록 → 와 ⏎로 바꿔서 찍어요.
const show = (text) => text.replace(/\t/g, ' → ').replace(/\r?\n/g, ' ⏎ ');
export function setup(api, log) {
  say = log;
  header = 'none';
  // 붙여넣기 결과는 이 이벤트 한 줄로만 알려요(Ctrl+V나 오른쪽 클릭 메뉴로 붙여도 같은 줄이 나와요).
  const off = api.on('cellsPasted', ({ pasted, skipped }) => log({
    ko: skipped > 0
      ? `${pasted}칸 바꿨고 ${skipped}칸은 값이 안 맞아서 건너뛰었어요`
      : `${pasted}칸 바꿨어요`,
    en: skipped > 0
      ? `${pasted} cells changed, ${skipped} skipped because the values did not fit`
      : `${pasted} cells changed`,
  }));
  return () => off();
}
// copyCells는 선택한 칸을 탭(칸 사이)과 줄바꿈(행 사이)으로 이은 글자를 돌려줘요. 엑셀에 붙여넣으면 그대로 표가 돼요.
// pasteCells는 그런 글자를 선택한 구간의 왼쪽 위 칸부터 채우고, 칸마다 편집과 같은 검증을 거쳐요.
// 직접 Ctrl+C, Ctrl+V를 눌러도 같은 일을 하고, 마우스 오른쪽 메뉴에도 복사·붙여넣기가 있어요.
export const actions = {
  header: (_api, value) => {
    header = value === 'columns' ? 'columns' : 'none';
  },
  copy: (api) => {
    const text = api.copyCells({ header });
    say({
      ko: text ? `복사한 글자: ${show(text)}` : '먼저 표에서 칸을 끌어서 골라 주세요',
      en: text ? `Copied text: ${show(text)}` : 'Drag across cells in the table first',
    });
  },
  // 선택한 구간의 왼쪽 위 칸부터 두 줄을 붙여요. 숫자 칸에 글자를 넣으면 값이 안 맞아서 건너뛰어요.
  pasteSample: (api) => {
    if (api.getSelectedCells().length === 0) {
      return say({
        ko: '먼저 표에서 칸을 골라 주세요 (붙여넣기는 고른 구간의 왼쪽 위 칸부터 채워요)',
        en: 'Select cells in the table first (paste fills from the top-left cell of the selection)',
      });
    }
    api.pasteCells('라떼 세트\t12\n말차 스무디\t아홉');
  },
};

Module files for a project with a bundler such as Vite. To run it with no setup, use the HTML tab or Try it.

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">
    <select aria-label="Headers" id="header">
      <option value="none" selected>Values only (default)</option>
      <option value="columns">Include headers</option>
    </select>
    <button type="button" id="copy">Copy selected cells</button>
    <button type="button" id="pasteSample">Paste test</button>
  </div>
  <div id="grid" style="height: 330px"></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('header').addEventListener('change', (event) => actions.header(api, event.target.value));
document.getElementById('copy').addEventListener('click', () => actions.copy(api));
document.getElementById('pasteSample').addEventListener('click', () => actions.pasteSample(api));
example.js
const menus = [
  'Americano',
  'Cafe Latte',
  'Vanilla Latte',
  'Cold Brew',
  'Cappuccino',
  'Green Tea Latte',
];
export const options = {
  columns: [
    { id: 'menu', title: 'Menu', width: 160, editable: true },
    { id: 'qty', title: 'Qty', kind: 'number', width: 90, editable: true },
    {
      id: 'price',
      title: 'Price',
      kind: 'number',
      width: 110,
      editable: true,
      formatValue: (value) => Number(value).toLocaleString('en-US'),
    },
  ],
  rows: menus.map((menu, i) => ({
    id: i + 1,
    menu,
    qty: 3 + ((i * 7) % 9),
    price: (4000 + i * 300) / 1000,
  })),
  rowKey: 'id',
  cellSelection: 'multiple',
};
let say = () => { };
let header = 'none';
// Print tabs and line breaks as → and ⏎ so they are visible.
const show = (text) => text.replace(/\t/g, ' → ').replace(/\r?\n/g, ' ⏎ ');
export function setup(api, log) {
  say = log;
  header = 'none';
  // The paste result is reported only by this one event line (Ctrl+V or the right-click menu give the same line).
  const off = api.on('cellsPasted', ({ pasted, skipped }) => log(skipped > 0
    ? `${pasted} cells changed, ${skipped} skipped because the values did not fit`
    : `${pasted} cells changed`));
  return () => off();
}
// copyCells returns the selected cells joined by tabs (between cells) and line breaks (between rows). Pasted into a spreadsheet, it becomes a table as is.
// pasteCells fills such text from the top-left cell of the selected range, and each cell goes through the same validation as editing.
// Pressing Ctrl+C and Ctrl+V yourself does the same thing, and the right-click menu has copy and paste too.
export const actions = {
  header: (_api, value) => {
    header = value === 'columns' ? 'columns' : 'none';
  },
  copy: (api) => {
    const text = api.copyCells({ header });
    say(text ? `Copied text: ${show(text)}` : 'Drag across cells in the table first');
  },
  // Paste two lines from the top-left cell of the selected range. Text in a number cell does not fit, so it is skipped.
  pasteSample: (api) => {
    if (api.getSelectedCells().length === 0) {
      return say('Select cells in the table first (paste fills from the top-left cell of the selection)');
    }
    api.pasteCells('Latte set\t12\nMatcha smoothie\tnine');
  },
};