본문 바로가기
프론트엔드 개발

엑셀 다운로드

by jyamin 2021. 11. 12.
728x90

button안에
onClick={() => this.download()}
넣어주고

클릭할 때 다운로드가 될 수 있도록

download() {
  const table = document.getElementsByTagName('table')[0];


let tab_text = '<html xmlns:x="urn:schemas-microsoft-com:office:excel">';
     tab_text += '<head><meta http-equiv="content-type" content="application/vnd.ms-excel; charset=UTF-8">';
     tab_text += '<xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet>'
     tab_text += '<x:Name>Test Sheet</x:Name>';
     tab_text += '<x:WorksheetOptions><x:Panes></x:Panes></x:WorksheetOptions></x:ExcelWorksheet>';
     tab_text += '</x:ExcelWorksheets></x:ExcelWorkbook></xml></head><body>';
     tab_text += "<table border='1px'>";

let exportTable = table.cloneNode(true);

tab_text += exportTable.outerHTML;
tab_text += '</table></body></html>';
let data_type = 'data:application/vnd.ms-excel';
let ua = window.navigator.userAgent;
let msie = ua.indexOf("MSIE ");
let fileName = this.period + '_Table' + '.xls';

if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) {
    if (window.navigator.msSaveBlob) {
        let blob = new Blob([tab_text], {
             type: "application/csv;charset=utf-8;"
        });
        navigator.msSaveBlob(blob, fileName);
    }
} else {
        let blob2 = new Blob([tab_text], {
              type: "application/csv;charset=utf-8;"
        });
        let filename = fileName;
        let elem = window.document.createElement('a');
        elem.href = window.URL.createObjectURL(blob2);
        elem.download = filename;
        document.body.appendChild(elem);
        elem.click();
        document.body.removeChild(elem);
    }
}

728x90

'프론트엔드 개발' 카테고리의 다른 글

react-router-dom이 안된다구?  (0) 2021.12.30
Script - /bin/csh: Event Not Found  (0) 2021.11.17
웹 렌더링 (Rendering on the Web)  (0) 2021.10.15
URI?? URL??  (0) 2021.10.08
React-Hooks : useState 연습하기  (0) 2021.10.08

댓글