js實現前端導出大文件Excel

//base64轉換成blob
function dataURIToBlob(dataURI, callback) {
  var binStr = atob(dataURI.split(",")[1]),
    len = binStr.length,
    arr = new Uint8Array(len);

  for (var i = 0; i < len; i++) {
    arr[i] = binStr.charCodeAt(i);
  }

  callback(new Blob([arr]));
}

var callback = function(blob) {
  var a = document.createElement("a");
  a.download = "數據" + ".xls";
  a.innerHTML = "download";
  // the string representation of the object URL will be small enough to workaround the browser‘s limitations
  a.href = URL.createObjectURL(blob);
  // you must revoke the object URL,
  //   but since we can‘t know when the download occured, we have to attach it on the click handler..
  a.click();
};

//下載導出
$(".down_box").click(function(e) {
  $.axs(
    host + "/digital/communication/exportData.action",
    {},
    function(data) {
      $(".down_box").css({ "pointer-events": "", opacity: "1" });
      var exportData = data.returnMap.exportData;
      // console.log(data.returnMap.exportData);
      //列標題
      let str =
        "<tr><td>數據時間</td><td>指標編號</td>" +
        "<td>指標名稱</td><td>機構號</td><td>機構名稱</td><td>機構層級</td>" +
        "<td>父機構號</td><td>父機構名稱</td><td>實時完成值</td><td>實時目標值</td><td>實時完成比</td><td>實時目標值差值</td>" +
        "<td>實時完成比排名</td><td>實時完成比紅綠字</td><td>實時完成預警值</td><td>上週實時</td><td>同比上週實時差值</td>" +
        "<td>同比上週實時</td><td>同比上週實時紅綠字</td></tr>";

      //循環遍歷,每行加入tr標籤,每一個單元格加td標籤
      for (let i = 0; i < exportData.length; i++) {
        str += "<tr>";
        for (let item in exportData[i]) {
          //增長\t爲了避免讓表格顯示科學計數法或者其餘格式
          str += `<td>${exportData[i][item] + "\t"}</td>`;
        }
        str += "</tr>";
      }
      //Worksheet名
      let worksheet = "Sheet1";
      let uri =
        "data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,";

      //下載的表格模板數據
      let template = `<html xmlns:o="urn:schemas-microsoft-com:office:office"
          xmlns:x="urn:schemas-microsoft-com:office:excel"
          xmlns="http://www.w3.org/TR/REC-html40">
          <head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet>
            <x:Name>${worksheet}</x:Name>
            <x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet>
            </x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]-->
            </head><body><table>${str}</table></body></html>`;
      //下載模板
      var template1 = uri + btoa(unescape(encodeURIComponent(template)));
      dataURIToBlob(template1, callback);
    },
    function() {
      $(".down_box").css({ "pointer-events": "", opacity: "1" });
    },
    function() {
      $(".down_box").css({ "pointer-events": "none", opacity: "0.5" });
    }
  );
});

  

HTMLjavascript

<div class="down_box">下載<div/>

  

備註: ajax部分爲封裝的ajax 能夠自行修改請求方式 css

數據格式:html

相關文章
相關標籤/搜索