js 之 浏览器导出
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <table id="targetTable"> <thead> <tr> <th>名次</th> <th>姓名</th> <th>成绩</th> </tr> </thead> <tbody> <tr align="center"> <td>1</td> <td>小明</td> <td>100</td> </tr> <tr align="center"> <td>2</td> <td>小红</td> <td>95.5</td> </tr> </tbody> </table> <button onclick="tableToExcel('targetTable', '成绩', 'daododd')">导出</button> <script type="text/javascript"> var tableToExcel = (function() { var uri = 'data:application/vnd.ms-excel;base64,', 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]--></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, filename) { if (!table.nodeType) table = document.getElementById(table) var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML} var nodea = document.createElement('a'); document.body.appendChild(nodea); nodea.href = uri + base64(format(template, ctx)); nodea.download = filename; nodea.click(); document.body.removeChild(nodea); } })() </script> </body> </html>