HTML 테이블 엑셀 다운로드 기능 개발 / Sheetjs 사용법

Sheetjs 사용법

Sheetjs 라이브러리 추가

<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.16.9/xlsx.full.min.js"></script>

head에 Sheetjs 라이브러리를 추가합니다.

엑셀 다운로드용 테이블 생성

<table id="excelTable" style="display:none;">
    <thead>
        <tr>
            <th>분류1</th>
            <th>분류2</th>
            <th>분류3</th>
            <th>분류4</th>
        </tr>
    </thead>
    <tbody id="excelTableBody">
    </tbody>
</table>

tbody를 유동적으로 변경하고, 엑셀 다운로드하기 위한 HTML table을 생성합니다.

엑셀 다운로드 기능 구현

function downloadExcel() {
    const errMsg = "엑셀파일 다운로드에 실패하였습니다. 관리자에게 문의해주세요.";

    // 다운로드 할 데이터 조회 후 테이블 채우기
    fetch('/ctgry/topic/getTopicExcel', {
        method: 'POST',
        headers: {
            "Content-Type": "application/json"
        },
        body: JSON.stringify({
            // 검색 파라미터 (페이징 파라미터 없이 조회)
            "parent_id": "null"
        })
    })
    .then((response) => response.json())
    .then((data) => {
        if(data.success == true) {
            // 엑셀 다운로드용 테이블 행 추가 처리
            let tableHtml = '';

            if(data.topicList.length > 0) {
                for (const ctgryMap of data.topicList) {
                    tableHtml += '<tr>';
                    tableHtml += '<td>' + ctgryMap.depth1 + '</td>';
                    tableHtml += '<td>' + ctgryMap.depth2 + '</td>';
                    tableHtml += '<td>' + ctgryMap.depth3 + '</td>';
                    tableHtml += '<td>' + ctgryMap.depth4 + '</td>';
                    tableHtml += '</tr>';
                }
            }

            document.getElementById('excelTableBody').innerHTML = tableHtml;

            // Sheetjs 사용하여 테이블 데이터로 엑셀 다운로드
            const excelTable = document.getElementById('excelTable');

            const wb = XLSX.utils.book_new();
            const ws = XLSX.utils.table_to_sheet(excelTable);

            ws["!cols"] = [
                { width: 20 },
                { width: 20 },
                { width: 20 },
                { width: 20 }
            ];

            XLSX.utils.book_append_sheet(wb, ws, "시트명");

            XLSX.writeFile(wb, ('엑셀파일명.xlsx'));

        }else {
            alert(errMsg);
        }
    })
    .catch((error) => {
        alert(errMsg);
    })
}

HTML table 데이터를 fetch로 조회하고, 엑셀 다운로드하는 javascript 함수 예시입니다.

Leave a comment