js 實現純前端將數據導出excel

上代碼:

<html>
<head>
  <p style="font-size: 20px;color: red;">使用a標籤方式將json導出csv文件</p>
  <button onclick='tableToExcel()'>導出</button>
</head>
<body>
  <script>
            
    function tableToExcel(){
      //要導出的json數據
      const jsonData = [
        {
          name:'路人甲',
          phone:'123456789',
          email:'[email protected]'
        },
        {
          name:'炮灰乙',
          phone:'123456789',
          email:'[email protected]'
        },
        {
          name:'土匪丙',
          phone:'123456789',
          email:'[email protected]'
        },
        {
          name:'流氓丁',
          phone:'123456789',
          email:'[email protected]'
        },
      ]
      //列標題,逗號隔開,每一個逗號就是隔開一個單元格
      let str = `姓名,電話,郵箱\n`;
      //增加\t爲了不讓表格顯示科學計數法或者其他格式
      for(let i = 0 ; i < jsonData.length ; i++ ){
        for(let item in jsonData[i]){
            str+=`${jsonData[i][item] + '\t'},`;     
        }
        str+='\n';
      }
      //encodeURIComponent解決中文亂碼
      let uri = 'data:text/csv;charset=utf-8,\ufeff' + encodeURIComponent(str);
      //通過創建a標籤實現
      let link = document.createElement("a");
      link.href = uri;
      //對下載的文件命名
      link.download =  "json數據表.xls";
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    }
 
</script>
</body>
</html>

 

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