在瀏覽器端直接操作 Excel 產生報表,雖然受限於 ActiveX 僅支援 IE,但在內部系統或特定環境下仍是快速產出格式化報表的有效手段。本文提供完整、帶註解的範例,涵蓋建立 Excel 應用程式、設定儲存格樣式、匯入 HTML 表格資料、自動調整欄寬等實用技巧。
function MakeExcel() {
var xls, xlBook, xlsheet;
try {
xls = new ActiveXObject('Excel.Application');
} catch (e) {
alert('請安裝 Excel 並啟用 ActiveX 控制項。');
return;
}
xls.visible = true;
xlBook = xls.Workbooks.Add;
xlsheet = xlBook.Worksheets(1);
// 合併標題列
xlsheet.Range(xlsheet.Cells(1,1), xlsheet.Cells(1,7)).MergeCells = true;
xlsheet.Range(xlsheet.Cells(1,1), xlsheet.Cells(1,7)).Value = '發卡記錄';
xlsheet.Rows(1).RowHeight = 25;
xlsheet.Rows(1).Font.Size = 14;
xlsheet.Rows(1).Font.Name = '黑體';
xlsheet.Columns('A:D').ColumnWidth = 18;
xlsheet.Columns(2).NumberFormatLocal = '@';
xlsheet.Columns(7).NumberFormatLocal = '@';
// 寫入欄位標題
var headers = ['卡號','密碼','計費方式','有效天數','金額','所屬服務項目','發卡時間'];
headers.forEach(function(h, i){ xlsheet.Cells(2, i+1).Value = h; });
// 從 HTML 表格讀取資料
var oTable = document.all['fors:data'];
var rowNum = oTable.rows.length;
for (var i = 2; i <= rowNum; i++) {
for (var j = 1; j <= 7; j++) {
xlsheet.Cells(i+1, j).Value = oTable.rows(i-1).cells(j-1).innerHTML;
}
}
// 統一樣式
xlsheet.Columns.AutoFit;
xlsheet.Range(xlsheet.Cells(1,1), xlsheet.Cells(rowNum+1,7)).HorizontalAlignment = -4108; // 置中
xlsheet.Range(xlsheet.Cells(2,1), xlsheet.Cells(rowNum+1,7)).Font.Size = 10;
xlsheet.Range(xlsheet.Cells(2,1), xlsheet.Cells(rowNum+1,7)).Borders.Weight = 2;
xls.UserControl = true; // 交由使用者控制,避免進程殘留
xls = xlBook = xlsheet = null;
}
<form id="fors" method="post" action="...">
<input type="button" value="生成excel文件" onclick="MakeExcel()" />
<table id="fors:data" border="1">
<thead><tr><th>卡號</th><th>密碼</th>...</tr></thead>
<tbody>
<tr><td>h000010010</td><td>543860</td>...</tr>
...
</tbody>
</table>
</form>
UserControl = true 並在結束時釋放物件參考。若需跨瀏覽器支援,推薦使用 SheetJS (xlsx) 或 ExcelJS 等純 JavaScript 函式庫,可在前端直接產出 .xlsx 檔案並觸發下載,無需 ActiveX。