function toExcel2() { var curTbl = document.getElementById("tableToEXC"); var oXL = new ActiveXObject("Excel.Application"); //创建AX对象excel var oWB = oXL.Workbooks.Add(); //获取workbook对象 var oSheet = oWB.ActiveSheet; //激活当前sheet var Lenr = curTbl.rows.length; //获取表格行数 for (i = 0; i < Lenr; i++) { var Lenc = curTbl.rows(i).cells.length; //取得表格行数 for (j = 0; j < Lenc; j++) { oSheet.Cells(i + 1, j + 1).value = curTbl.rows(i).cells(j).innerText; //赋值 } } oXL.Visible = true; //设置excel可见属性 }
直接上代码:
<html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> <script type="text/javascript"> function toExcel() { var curTbl = document.getElementById("tableToEXC"); 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; } </script> </head> <body> <form id="form1" runat="server"> <div> <table id="tableToEXC"> <thead> <tr> <td>姓名</td> <td>年龄</td> <td>地址</td> </tr> </thead> <tbody> <tr> <td>tom</td> <td>12</td> <td>beijing</td> </tr> <tr> <td>tom</td> <td>12</td> <td>beijing</td> </tr> <tr> <td>tom</td> <td>12</td> <td>beijing</td> </tr> </tbody> </table> <input type="button" onclick="toExcel()" /> </div> </form> </body> </html>
如果报错:
安全模式设置成“中”,如果javascript脚本中报这个错误,还应将IE的安全设置“不允许运行未标记为安全的activeX控件”启用即可。
注意如果您将相应的网站设成“受信任的站点”,必须对“受信任的站点”进行相应的IE安全设置,此时如果对“Internet”IE设置将是徒劳的。