標籤:index trident div color encode button .exe range 自己
因同事的需求是想前端匯出excel表格,網上找了一些demo,自己修改了一下,可能以後會用到,記錄下來吧,相容ie和一些主流瀏覽器,ie可能會報錯,原因參考 這裡,edge 瀏覽器還沒有辦法匯出,正在嘗試...
<!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8"> <title>table 匯出excel表格</title> </head> <body> <div> <button type="button" onclick="exportExcel(‘tableExcel‘)">匯出Excel</button> </div> <div id="myDiv"> <table id="tableExcel" width="100%" border="1" cellspacing="0" cellpadding="0"> <tr> <td colspan="5" align="center">html 表格匯出道Excel</td> </tr> <tr> <td>欄位標題1</td> <td>欄位標題2</td> <td>類標題3</td> <td>欄位標題4</td> <td>欄位標題5</td> </tr> <tr> <td>aaa</td> <td>bbb</td> <td>ccc</td> <td>ddd</td> <td>eee</td> </tr> <tr> <td>AAA</td> <td>BBB</td> <td>CCC</td> <td>DDD</td> <td>EEE</td> </tr> <tr> <td>FFF</td> <td>GGG</td> <td>HHH</td> <td>III</td> <td>JJJ</td> </tr> </table> </div> <script> var idTmr; function getExplorer() { var explorer = window.navigator.userAgent; console.log(explorer); //ie if (explorer.indexOf("Trident") >= 0) { return ‘ie‘; } //firefox else if (explorer.indexOf("Firefox") >= 0) { return ‘Firefox‘; } //Chrome else if(explorer.indexOf("Chrome") >= 0){ return ‘Chrome‘; } //Opera else if(explorer.indexOf("Opera") >= 0){ return ‘Opera‘; } //Safari else if(explorer.indexOf("Safari") >= 0){ return ‘Safari‘; } } function exportExcel(tableid) { if(getExplorer()==‘ie‘){ var curTbl = document.getElementById(tableid); var oXL = new ActiveXObject("Excel.Application"); var oWB = oXL.Workbooks.Add(); var oSheet = oWB.ActiveSheet; var sel = document.body.createTextRange(); sel.moveToElementText(curTbl); sel.select(); sel.execCommand("Copy"); oSheet.Paste(); oXL.Visible = true; } else{ tableToExcel(tableid) } } var tableToExcel = (function() { var uri = ‘data:application/vnd.ms-excel;base64,‘, template = ‘<html><head><meta charset="UTF-8"></head><body><table>{table}</table></body></html>‘, base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) }, format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; }) } return function(table, name) { if (!table.nodeType) table = document.getElementById(table) var ctx = {worksheet: name || ‘Worksheet‘, table: table.innerHTML} window.location.href = uri + base64(format(template, ctx)) } })(); </script> </body></html>
原文來自: 這裡
原生JavaScript 匯出excel表格(相容ie和其他主流瀏覽器)