JS 匯出網頁中Table內容到excel
阿新 • • 發佈:2019-01-03
<html> <head> <script type="text/javascript" language="javascript"> var idTmr; function method1(tableid) {//整個表格拷貝到EXCEL中 var curTbl = document.getElementById(tableid); var oXL = new ActiveXObject("Excel.Application"); //建立AX物件excel var oWB = oXL.Workbooks.Add(); //獲取workbook物件 var xlsheet = oWB.Worksheets(1); //啟用當前sheet var sel = document.body.createTextRange(); sel.moveToElementText(curTbl); //把表格中的內容移到TextRange中 sel.select(); //全選TextRange中內容 sel.execCommand("Copy"); //複製TextRange中內容 xlsheet.Paste(); //貼上到活動的EXCEL中 oXL.Visible = true; //設定excel可見屬性 try { var fname = oXL.Application.GetSaveAsFilename("將Table匯出到Excel.xls", "Excel Spreadsheets (*.xls), *.xls"); } catch (e) { print("Nested catch caught " + e); } finally { oWB.SaveAs(fname); oWB.Close(savechanges = false); //xls.visible = false; oXL.Quit(); oXL = null; //結束excel程序,退出完成 //window.setInterval("Cleanup();",1); idTmr = window.setInterval("Cleanup();", 1); } } function Cleanup() { window.clearInterval(idTmr); CollectGarbage(); } </script> </head> <body> <table id="ta"> <tr> <td>1</td><td>admin</td> <td>23</td><td>程式設計師</td> <td>天津</td><td>
[email protected]</td> </tr> <tr> <td>2</td><td>guest</td> <td>23</td><td>測試員</td> <td>北京</td><td>[email protected]</td> </tr> </table> <input id="Button1" type="button" value="匯出EXCEL" onclick="javascript:method1('ta')" /> </body> </html>
或者:
<html>
<head>
<script type="text/javascript">
function dataToExcel(tableid) {//整個表格拷貝到EXCEL中
var curTbl = document.getElementById(tableid);
var oXL;
try {
oXL = GetObject("", "Excel.Application");
}
catch (E) {
try {
oXL = new ActiveXObject("Excel.Application");
}
catch (E2) {
//alert("Please confirm:\n1.Microsoft Excel has been installed.\n2.Internet
Options=>Security=>Setting \"Enable unsafe ActiveX\"");
alert("請確認:\n1.機器上Excel已經安裝.\n2.Internet 選項=>安全=>Internet \"對
未標記為安全的ActiveX控制元件進行初始化和指令碼執行,設定為啟用\"");
return;
}
}
//建立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可見屬性
}
</script>
</head>
<body>
<table id="ta">
<tr>
<td>1</td><td>admin</td>
<td>23</td><td>程式設計師</td>
<td>天津</td><td> [email protected]</td>
</tr>
<tr>
<td>2</td><td>guest</td>
<td>23</td><td>測試員</td>
<td>北京</td><td>[email protected]</td>
</tr>
</table>
<input id="Button1" type="button" value="匯出EXCEL"
onclick="javascript:dataToExcel('ta')" />
</body>
</html>