본문 바로가기
프론트엔드/javascript

엑셀 다운로드

by 느바 2023. 10. 27.
반응형

엑셀 다운로드

 

Blob 이해

https://heropy.blog/2019/02/28/blob/

 

Blob(블랍) 이해하기

JavaScript에서 Blob(Binary Large Object, 블랍)은 이미지, 사운드, 비디오와 같은 멀티미디어 데이터를 다룰 때 사용할 수 있습니다. 대개 데이터의 크기(Byte) 및 MIME 타입을 알아내거나, 데이터를 송수신

heropy.blog

 

자바스크립트로 엑셀 다운로드 하는 예제 코드

- JSON 데이터 -> HTML 변환 -> 엑셀 다운로드

- 한글 꺠짐 방지를 위해 utf-8 bom 문자열 "\ufeff"를 Blob 생성시 array 인수에 붙여준다.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>

    <button class="Download" onclick="Download()">Download Excel</button>
    <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
    <script>
      /** ### DOWNLOADING EXCEL FILE FROM JSON DATA ### **/
      //Copy the Json to this variable.
      function Download() {
        var myList = [
          {
            "Book ID": "1",
            "Book Name": "철수",
            "Category": "mobile",
            "Price": "120.60",
            "Hi": "125.60",
          },
          {
            "Book ID": "2",
            "Book Name": "Asp.Net 4 Blue Book",
            "Category": "Computers",
            "Price": "225.60",
            "Hi": "225.60",
          },
          {
            "Book ID": "3",
            "Book Name": "Popular Science",
            "Category": "AP",
            "Price": "325.60",
            "Hi": "325.60",
          },
        ];

        //here we are crating a vertual html page using JavaScript whih can not be show in the body of our page.
        var html = document.createElement("html");
        var head = document.createElement("head");
        html.appendChild(head);
        var body = document.createElement("body");
        html.appendChild(body);
        var div = document.createElement("div");
        body.appendChild(div);
        var table = document.createElement("table");
        table.id = "excelDataTable";
        table.border = "1";
        div.appendChild(table);

        //Styling the Table
        var style = document.createElement("style");
        head.appendChild(style);
        style.type = "text/css";

        //you can change the style of the excel header and body rows here.
        var styleText = `.innerTableData { background-color:tomato;color:white;font-weight: bold; } 
          td { background-color:beige; }`;
        style.innerHTML = styleText;

        document.body.appendChild(html);

        //this for loop will create the header data for the html table from the given json data key.
        var columns = [];
        var headerTr$ = $("<tr/>");

        for (var i = 0; i < myList.length; i++) {
          var rowHash = myList[i];
          for (var key in rowHash) {            
            if ($.inArray(key, columns) == -1) {
              columns.push(key);
              headerTr$.append($('<td class = "innerTableData"/>').html(key));
            }
          }
        }
        $("#excelDataTable").append(headerTr$);

        //this for loop will create the row data for the html table from the given json data.
        for (var i = 0; i < myList.length; i++) {
          var row$ = $("<tr/>");
          for (var colIndex = 0; colIndex < columns.length; colIndex++) {
            var cellValue = myList[i][columns[colIndex]];
            if (cellValue == null) {
              cellValue = "";
            }
            row$.append($("<td/>").html(cellValue));
          }
          $("#excelDataTable").append(row$);
        }

        //here we are adding the html file of the table and get the values then convert it to ms-excel formate.
        let file = new Blob(["\ufeff" + html.outerHTML], {type: "application/vnd.ms-excel"});//utf-8 bom 문자열 추가 하여 한글 꺠짐 방지
        let url = URL.createObjectURL(file);

        //this is the file name after downloading the excel file.
        //you can change the text which is here "downloadedfile"
        //Note one thing dont remove the second part of this string ".xls"
        //other wise the file downloaded can not work.
        var filename = "downloadedfile" + ".xls";

        //here we are creating HTML <a> Tag which can be trigger to download the excel file.
        var a = document.createElement("a");
        a.id = "export";

        document.body.appendChild(a);

        //here we are checking if the bwoswer is IE or not if IE then we use window.navigator.msSaveBlob function otherwise
        //Go with Simple Blob file.
        if (window.navigator && window.navigator.msSaveBlob) {
          window.navigator.msSaveBlob(file, filename);
          a.click();
          document.body.removeChild(a);
          document.body.removeChild(html);
        } else {
          a.download = filename;
          a.href = url;
          a.click();
          document.body.removeChild(a);
          document.body.removeChild(html);
        }
        URL.revokeObjectURL(url);
      }
    </script>
  </body>
</html>

 

https://codepen.io/dimorin/pen/oNmjNbo

 

Excel Download Works in every Browser

...

codepen.io

 

반응형

'프론트엔드 > javascript' 카테고리의 다른 글

부동소수점 오류 현상  (0) 2024.03.08
금액 입력 input 구현  (0) 2023.12.29
SVG 애니메이션 만들기  (0) 2023.10.17
TOAST UI DateRangePicker 날짜 초기화  (0) 2023.10.17
SPA에서 History API 이해  (0) 2023.10.16