标签:
不使用服务器端的技术,直接使用js将网页中的表格数据导出为excel文件,支持所有浏览器;
前提条件是:网页中的表格数据必须使用table标签排版且不能有任何错误。
<!DOCTYPE HTML> <html> <head> <title>javascript exportExcel</title> </head> <body> <table id="name" border="1" cellspacing="0" cellpadding="10"> <tr> <th>name</th> <th>age</th> <th>job</th> </tr> <tr> <td>Mike</td> <td>22</td> <td>Designer</td> </tr> <tr> <td>David</td> <td>28</td> <td>Programmer</td> </tr> </table> <br> <button onclick="exportExcel(‘name‘);">export to excel</button> <body> <script> /** * 将html中的表格导出为excel(兼容所有浏览器) * @param {[type]} tableId [表格的id] */ function exportExcel(tableId) { var idTmr; if (/msie|trident/i.test(navigator.userAgent)) { var curTbl = document.getElementById(tableId), oXL = new ActiveXObject(‘Excel.Application‘), oWB = oXL.Workbooks.Add(), //创建AX对象excel xlsheet = oWB.Worksheets(1), //获取workbook对象 sel = document.body.createTextRange(); //激活当前sheet sel.moveToElementText(curTbl); //把表格中的内容移到TextRange中 sel.execCommand("Copy"); //复制TextRange中内容 xlsheet.Paste(); //粘贴到活动的EXCEL中 oXL.Visible = true; //设置excel可见属性 try { var fname = oXL.Application.GetSaveAsFilename(‘Excel.xls‘, ‘Excel Spreadsheets (*.xls), *.xls‘); } catch (e) { print(‘Nested catch caught‘ + e); } finally { oWB.SaveAs(fname); oWB.Close(savechanges = false); oXL.Quit(); oXL = null; idTmr = setInterval(function() { clearInterval(idTmr); CollectGarbage(); }, 1); } } else { function base64(s) { return btoa(unescape(encodeURIComponent(s))) }; function format(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; }); }; 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>‘, ctx = { worksheet: name || ‘Worksheet‘, table: document.getElementById(tableId).innerHTML }; location.href = uri + base64(format(template, ctx)) } } </script> </html>
标签:
原文地址:http://www.cnblogs.com/happyfreelife/p/5379261.html