JS导出EXCEL的两种方法
function method1(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 sel = document.body.createTextRange();
??? sel.moveToElementText(curTbl);
??? //把表格中的内容移到TextRange中
??? sel.select();
??? //全选TextRange中内容
??? sel.execCommand("Copy");
??? //复制TextRange中内容
??? oSheet.Paste();
??? //粘贴到活动的EXCEL中??????
??? oXL.Visible = true;
??? //设置excel可见属性
}
function method2(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可见属性
}
<input type="button" onclick="javascript:method1('TableExcel');" value="第一种方法导入到EXCEL">
<input type="button" onclick="javascript:method2('TableExcel');" value="第二种方法导入到EXCEL">
?