2016-08-24 207 views
-1

我正在使用以下代碼將HTML數據提取到Excel中。當我點擊下載鏈接時,它下載一個excel文件,但是它的空白並且不包含任何數據。下載的文件大小爲1KB。有沒有人遇到過這樣的問題 ?將HTML表格數據導出到Excel

<!DOCTYPE html> 
    <html> 
    <head> 
    <meta http-equiv="content-type" content="application/vnd.ms-excel; charset=UTF-8"> 
    <meta charset="UTF-8" /> 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.3/jquery.min.js"></script> 
    <script lang="js"> 
     function fnExcelReport() { 
      var tab_text = '<html xmlns:x="urn:schemas-microsoft-com:office:excel">'; 
      tab_text = tab_text + '<head><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet>'; 

      tab_text = tab_text + '<x:Name>Test Sheet</x:Name>'; 

      tab_text = tab_text + '<x:WorksheetOptions><x:Panes></x:Panes></x:WorksheetOptions></x:ExcelWorksheet>'; 
      tab_text = tab_text + '</x:ExcelWorksheets></x:ExcelWorkbook></xml></head><body>'; 

      tab_text = tab_text + "<table border='1px'>"; 
      tab_text = tab_text + $('#myTable').html(); 
      tab_text = tab_text + '</table></body></html>'; 

      var data_type = 'data:application/vnd.ms-excel'; 

      var ua = window.navigator.userAgent; 
      var msie = ua.indexOf("MSIE "); 

      if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) { 
       if (window.navigator.msSaveBlob) { 
        var blob = new Blob([tab_text], { 
         type: "application/csv;charset=utf-8;" 
        }); 
        navigator.msSaveBlob(blob, 'Test file.xls'); 
       } 
      } else { 
       $('#test').attr('href', data_type + ', ' + encodeURIComponent(tab_text)); 
       $('#test').attr('download', 'Test file.xls'); 
      } 

     } 
    </script> 
</head> 
<body> 
    <a href="#" id="test" onClick="javascript:fnExcelReport();">download</a> 

    <table id="myTable"> 
     <thead> 
      <tr> 
       <td style="padding-right: 30px;"><b>Name</b> 

       </td> 
       <td style="padding-right: 30px;"><b>Age</b> 

       </td> 
      </tr> 
     </thead> 
     <tbody> 
      <tr> 
       <td>Tester1</td> 
       <td>30</td> 
      </tr> 
      <tr> 
       <td>Tester2</td> 
       <td>29</td> 
      </tr> 
      <tr> 
       <td>Tester3</td> 
       <td>17</td> 
      </tr> 
     </tbody> 
    </table> 
</body> 
</html> 

回答

0

沒有下載的Excel不爲空,有數據說是「tab_text」變量, 嘗試打開Excel用記事本文件。你想在excel中保存什麼樣的數據?將它保持爲'\ n'行分隔,並用','分隔列。

+0

我希望一旦打開下載的excel,就可以在excel中顯示html表格數據。你能告訴我我該怎麼做? –