萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

IE 專用:用 JavaScript 將網頁匯出至 Excel 並列印

利用 IE 專屬的 ActiveXObject 與 ExecCommand,可將網頁表格內容複製並貼上至 Excel,或呼叫瀏覽器列印功能。僅適用於 IE 瀏覽器,現代瀏覽器(Edge、Chrome、Firefox)不支援。

完整頁面範例

<html>
<head>
<title>IE 匯出 Excel 與列印</title>
<style>
.table_stat { border-right:0; border-bottom:0; border-left:1px solid #819BD8; border-top:1px solid #819BD8; }
.td_stat { border-right:1px solid #819BD8; border-bottom:1px solid #819BD8; }
</style>
</head>
<body>
<!-- 必須放置一個隱藏的 WebBrowser ActiveX 元件 -->
<object classid="CLSID:8856F961-340A-11DO-A96B-00C04FD705A2" height="0" id="WebBrowser" width="0"></object>

<table width="100%" align="center" class="table_stat">
    <tr><td class="td_stat" colspan="2">用戶信息</td></tr>
    <tr>
        <td class="td_stat">姓名</td>
        <td class="td_stat">張三</td>
    </tr>
    <tr>
        <td class="td_stat" colspan="2">
            <input type="button" id="export" value="匯出" onclick="exportToExcel()" />
            <input type="button" id="print" value="列印" onclick="printPage()" />
        </td>
    </tr>
</table>

<script type="text/javascript">
// 匯出至 Excel
function exportToExcel() {
    if (!document.getElementById("title")) return;
    try {
        var oRangeRef = document.body.createTextRange();
        oRangeRef.execCommand("Copy");
        var appExcel = new ActiveXObject("Excel.Application");
        appExcel.visible = true;
        appExcel.Workbooks.Add().WorkSheets.Item(1).Paste();
    } catch(e) {
        alert("匯出失敗:" + e.message);
    }
}

// 列印頁面
function printPage() {
    if (!document.getElementById("title")) return;
    var exportBtn = document.getElementById("export");
    var printBtn = document.getElementById("print");
    try {
        exportBtn.style.display = "none";
        printBtn.style.display = "none";
        document.all.WebBrowser.ExecWB(6, 1); // 6=PRINT, 1=DONTPROMPTUSER
    } catch(e) {
        alert("列印失敗:" + e.message);
    }
    exportBtn.style.display = "";
    printBtn.style.display = "";
}
</script>
</body>
</html>

關鍵技術點

  • createTextRange() + execCommand("Copy"):將整個 body 內容複製到剪貼簿。
  • new ActiveXObject("Excel.Application"):啟動 Excel 進程(需使用者允許 ActiveX)。
  • WebBrowser.ExecWB(6,1):呼叫 IE 內建列印命令,6 為列印,1 為不提示對話框。
  • 列印前隱藏按鈕,列印後恢復,避免列印出按鈕。

現代跨瀏覽器替代方案

  • 匯出 Excel:SheetJS (xlsx.js)、ExcelJS、後端產生 .xlsx 下載。
  • 列印:window.print() 配合 @media print CSS 隱藏不需列印元素。
  • 表格匯出:DataTables Buttons 擴充、table2excel 等 jQuery 外掛。
注意:此方案僅適合內部 IE 專用系統,對外網站請勿使用。
copyright © 萬盛學電腦網 all rights reserved