JS 導入Excel數據

需要依賴 xlsx.js 插件,插件可自行到官網下載最新依賴

 

效果圖:

 

 

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>JS Excel導入表格數據</title>
  <style>
    table {
      border: 1px solid black;
      border-collapse: collapse;
    }

    th,
    td {
      padding: 5px;
    }
  </style>
</head>

<body>
  <input type="file" onchange="readExcel(this)" />
  <div id="d1"></div>
  <script src="xlsx.full.min.js"></script>
  <script>
    function readExcel(file_obj) {
      let reader = new FileReader();
      let file = file_obj.files[0];
      reader.readAsBinaryString(file);
      reader.onload = function (e) {
        let data = e.target.result;
        let wb = XLSX.read(data, { type: 'binary' });
        sheetName = wb.SheetNames[0] // 獲取文檔中第一個sheet頁籤的名字
        sheets = wb.Sheets[sheetName] // 獲sheet名頁簽下的數據
        // console.log(sheets);
        const htmlList = XLSX.utils.sheet_to_json(sheets) // sheet頁籤的內容轉化爲json數據
        // console.log(htmlList);

        let html = ''
        let state = false // 判斷是否表格
        for (const item of htmlList) {
          // 開始渲染表格,設置屬性
          if (item.__EMPTY === '        <table>') {
            state = true
            item.__EMPTY = '        <table border="1" id="mytable">'
          }

          // 結束渲染表格
          if (item.__EMPTY === '        </table>') {
            state = false
            html += item.__EMPTY
          }
          if (state === false) continue

          // 渲染格子
          for (const key in item) {
            const element = item[key];
            html += element
          }
        }
        document.getElementById('d1').innerHTML = html
      };
    }</script>
</body>
</html>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章