js:
function method(tableid) //读取表格中每个单元到EXCEL中 { var curTbl = document.getElementById(tableid); 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:
<table id="TableExcel"> <tr> <td>姓名</td> <td>性别</td> <td>爱好</td> </tr> <tr> <td>张三</td> <td>男</td> <td>篮球</td> </tr> <tr> <td>李四</td> <td>男</td> <td>绘画</td> </tr> <tr> <td>王五</td> <td>女</td> <td>钢琴</td> </tr> </table> <input type="button" onclick="javascript:method('TableExcel');" value="第二种方法导入到EXCEL"> <script>
必须修改浏览器的默认设置。设置方法为:
工具->Internet选项->安全->自定义级别->对没有标记安全级别的ActiveX控件进行初始化设为启用