재우니의 블로그

 

 

html 의 table 을 copy 기능 넣어 excel 붙여넣기 (execCommand("copy"))

 

 

html 의 table 형태를 엑셀에 붙여넣기 하고자 할 때가 있습니다. 이는 클립보드 함수를 활용하여 엑셀에 복사할 수 있게 스크립트를 구현해야 합니다.

 

<table id="dataTable" class="centered base-table highlight">
    <thead>
        <tr>
            <th class="grey lighten-4" style="width: 70px;">이름</th>
            <th class="grey lighten-4" style="width: 100px;">직책</th>
            <th class="grey lighten-4">연차수당</th>
            <th class="grey lighten-4">개인 정성평가</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>홍길동</td>
            <td>팀장</td>
            <td>50,000</td>
            <td>600,000</td>
        </tr>
    </tbody>
</table>


<br>
<button id="copyButton">Copy to Excel</button>

 

 

버튼 이벤트에 대한 구현입니다. table 의 html 형태에서 row 개수만큼의 내용을 textContent 속성을 통해 값을 얻습니다. 그리고 clipboardData 배열에 하나씩 담습니다. 엑셀 구분자는 \t 이며 이를 통해 한줄씩 저장합니다.

textarea 를 생성하여 배열값을 담아 바인딩 하고, 이를 select() 함수를 통해 클립보드 복사(copy) 합니다.

 

document.getElementById("copyButton").addEventListener("click", function () {
    const table = document.getElementById("dataTable");
    const rows = table.rows;
    const clipboardData = [];

    for (let i = 0; i < rows.length; i++) {
        const row = rows[i];
        const rowData = [];

        for (let j = 0; j < row.cells.length; j++) {
            rowData.push(row.cells[j].textContent);
        }

        clipboardData.push(rowData.join("\t")); // Use tab as a separator for Excel
    }

    const clipboardText = clipboardData.join("\n"); // Use newline to separate rows

    const tempTextArea = document.createElement("textarea");
    tempTextArea.value = clipboardText;
    document.body.appendChild(tempTextArea);
    tempTextArea.select();
    document.execCommand("copy");
    document.body.removeChild(tempTextArea);

    alert("Table data copied to clipboard. You can now paste it into Excel.");
});

 

 

참고자료

 

https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand

 

Document: execCommand() method - Web APIs | MDN

When an HTML document has been switched to designMode, its document object exposes an execCommand method to run commands that manipulate the current editable region, such as form inputs or contentEditable elements.

developer.mozilla.org