투케이2K

253. (JavaScript) [SheetJS 라이브러리] - SheetJS 라이브러리 사용해 html table 테이블을 excel 엑셀 파일로 저장 실시 본문

JavaScript

253. (JavaScript) [SheetJS 라이브러리] - SheetJS 라이브러리 사용해 html table 테이블을 excel 엑셀 파일로 저장 실시

투케이2K 2023. 2. 18. 18:09
반응형

[개발 환경 설정]

개발 툴 : Edit++

개발 언어 : JavaScript

 

[소스 코드]

    <!-- 내부 CSS 스타일 지정 -->
    <style>

        table {border: 2px solid; border-collapse: collapse; text-align: center;}

        th, td {border: 1px solid; padding: 10px 5px;}

        th{background: #000000; color: #ffffff;}

    </style>




    <!-- [CDN 설정 실시] -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.15.5/xlsx.full.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.8/FileSaver.min.js"></script>





    <!-- [내부 자바스크립트 J쿼리 이벤트 지정] -->
    <script>
        

        /*
        -----------------------------------------
        [요약 설명]
        -----------------------------------------
        1. window.onload : 웹페이지 로드 완료 상태를 확인합니다
        -----------------------------------------
        2. SheetJS : 배열, json, html 등 다양한 형태의 데이터로 엑셀 파일을 생성할 수 있으며, 생성된 excel 파일을 읽을 수 있는 라이브러리 입니다
        -----------------------------------------
        3. 참고 사이트 : 

        https://github.com/SheetJS/sheetjs

        https://redstapler.co/sheetjs-tutorial-create-xlsx/

        -----------------------------------------
        */






        // [html 최초 로드 및 이벤트 상시 대기 실시] 
        window.onload = function() {
            console.log("");
            console.log("=========================================");
            console.log("[window onload] : [start]");
            console.log("=========================================");
            console.log("");
        };




        // [자바스크립트 테스트 코드]
        function saveExcelFile() {
            console.log("");
            console.log("=========================================");
            console.log("[saveExcelFile] : [start]");
            console.log("=========================================");
            console.log("");

            // [1] : [파일 명칭 지정]
            var fileName = "Test.xlsx"


            // [2] : [테이블 데이터 시트에 삽입]
            var wb = XLSX.utils.table_to_book(document.getElementById('mytable'), {sheet:"Test Sheet",raw:true});


            // [3] : [엑셀 파일 만들기]
            XLSX.writeFile(wb, (fileName));
        };



    </script>





<body>


    <!-- [버튼 생성] -->
    <input type="button" id="excelFileExport" value="엑셀 파일 다운로드" onclick="saveExcelFile();" />


    <!-- [테이블 생성] -->
    <table id="mytable">
        <thead>
            <tr>
                <th>사용자</th>
                <th>나이</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>투케이</td>
                <td>29</td>
            </tr>
            <tr>
                <td>TWOK</td>
                <td>30</td>
            </tr>
        </tbody>
    </table>


</body>
 

[결과 출력]


 

반응형
Comments