DQ NO.1 - dragon quest fans club

 找回密碼
 加入成為夥伴
搜索
熱搜: 活動 交友 discuz
查看: 6612|回復: 0

[JS] Javascript 將HTML Table 轉成EXCEL下載

[複製鏈接]
發表於 2014-3-26 15:10:43 | 顯示全部樓層 |閱讀模式
說明:
  將HTML中的table透過javascript轉成EXCEL檔案下載(可相容utf-8)。

======================================


HTML

  1.         <table id="Data" style="font-family:微軟正黑體">
  2.                 <thead>
  3.                         <tr>
  4.                                 <td >no.</td>
  5.                                 <td>Date</td>
  6.                                 <td>StockCode</td>
  7.                                 <td>Value</td>
  8.                                 <td>Last Update</td>
  9.                         </tr>
  10.                 </thead>
  11.                 <tbody>
  12.                
  13.                         <tr>
  14.                                 <td colspan="5"> 目前沒有資料</td>
  15.                         </tr>
  16.                
  17.                 </tbody>
  18.         
  19.         </table>
複製代碼




Javascript




  1. <script type="text/javascript">

  2. var tableToExcel = (function() {
  3.   var uri = 'data:application/vnd.ms-excel;base64,'
  4.     , 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]--><meta http-equiv="content-type" content="text/plain; charset=UTF-8"/></head><body><table>{table}</table></body></html>'
  5.     , base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) }
  6.     , format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; }) }
  7.   return function(table, name) {
  8.     if (!table.nodeType) table = document.getElementById(table)
  9.     var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML}
  10.     window.location.href = uri + base64(format(template, ctx))
  11.   }
  12. })()
  13. </script>
複製代碼

相關帖子

您需要登錄後才可以回帖 登錄 | 加入成為夥伴

本版積分規則

Archiver|手機版|ぱふぱふ屋|DQ NO.1

GMT+8, 2024-4-19 10:11 , Processed in 0.024496 second(s), 20 queries .

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回復 返回頂部 返回列表