萬盛學電腦網

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

JavaScript 將網頁內容匯出為 Word / Excel 檔案(ActiveXObject 方案與現代替代)

歷史方案:ActiveXObject(僅限 IE / Windows)

原文使用 new ActiveXObject('Excel.Application')、new ActiveXObject('Word.Application') 自動化 Office 應用程式,僅在 IE 且已安裝 Office 的環境可用,**現代瀏覽器(Chrome、Firefox、Edge)完全不支援**,且有嚴重安全限制。

程式碼存檔(僅供參考)

// 匯出指定區域到 Excel
function AllAreaExcel() {
    const oXL = new ActiveXObject('Excel.Application');
    const oWB = oXL.Workbooks.Add();
    const oSheet = oWB.ActiveSheet;
    const range = document.body.createTextRange();
    range.moveToElementText(document.getElementById('PrintA'));
    range.select(); range.execCommand('Copy');
    oSheet.Paste();
    oXL.Visible = true;
}

// 匯出表格單元格逐儲存格寫入 Excel
function CellAreaExcel() {
    const oXL = new ActiveXObject('Excel.Application');
    const oWB = oXL.Workbooks.Add();
    const oSheet = oWB.ActiveSheet;
    const table = document.getElementById('PrintA');
    for (let i = 0; i < table.rows.length; i++) {
        for (let j = 0; j < table.rows[i].cells.length; j++) {
            oSheet.Cells(i+1, j+1).value = table.rows[i].cells[j].innerText;
        }
    }
    oXL.Visible = true;
}

// 匯出到 Word
function AllAreaWord() {
    const oWD = new ActiveXObject('Word.Application');
    const oDC = oWD.Documents.Add();
    const range = document.body.createTextRange();
    range.moveToElementText(document.getElementById('PrintA'));
    range.select(); range.execCommand('Copy');
    oDC.Range(0,1).Paste();
    oWD.Visible = true;
}

現代跨瀏覽器方案

1. 純前端生成檔案下載(推薦)

2. SheetJS 匯出表格為 Excel 範例

<script src="https://cdn.sheetjs.com/xlsx-latest/package/dist/xlsx.full.min.js"></script>
<button onclick="exportTableToExcel('dataTable', '報表.xlsx')">匯出 Excel</button>

<script>
function exportTableToExcel(tableId, filename) {
    const table = document.getElementById(tableId);
    const wb = XLSX.utils.table_to_book(table, { sheet: 'Sheet1' });
    XLSX.writeFile(wb, filename);
}
</script>

3. docx 庫匯出 Word 範例

<script src="https://unpkg.com/docx@8.0.0/build/index.umd.js"></script>
<button onclick="exportToWord()">匯出 Word</button>

<script>
async function exportToWord() {
    const { Document, Packer, Paragraph, TextRun } = docx;
    const doc = new Document({
        sections: [{
            children: [
                new Paragraph({ children: [new TextRun({ text: '匯出標題', bold: true, size: 32 })] }),
                new Paragraph({ children: [new TextRun('內容段落...')] })
            ]
        }]
    });
    const blob = await Packer.toBlob(doc);
    saveAs(blob, '文件.docx'); // 需 FileSaver.js 或自行創建 a[download]
}
</script>

4. 伺服器端生成(大數據/複雜樣式)

Node.js 使用 exceljs、docx、puppeteer (HTML 轉 PDF) 等在後端生成,前端僅下載連結,效能與相容性最佳。

總結

ActiveXObject 方案已淘汰。**現代專案請採用前端庫(SheetJS、docx)或後端生成**,實現跨平台、無依賴、安全的檔案匯出功能。

copyright © 萬盛學電腦網 all rights reserved