原文使用 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;
}
Blob 下載。<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>
<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>
Node.js 使用 exceljs、docx、puppeteer (HTML 轉 PDF) 等在後端生成,前端僅下載連結,效能與相容性最佳。
ActiveXObject 方案已淘汰。**現代專案請採用前端庫(SheetJS、docx)或後端生成**,實現跨平台、無依賴、安全的檔案匯出功能。