在企業級項目中,把頁面數據導出為 Excel 報表是非常實用的功能。本文將詳細講解如何借助 JavaScript 調用本地的 Excel 應用來生成報表,並附上帶有完整註釋的實例,方便大家參考借鑑。
整個功能的關鍵在於通過 ActiveXObject 創建 Excel 應用實例,再逐格寫入數據、設置樣式。以下為帶註釋的核心代碼:
function MakeExcel(){
var i, j;
try {
var xls = new ActiveXObject("Excel.Application");
}
catch(e) {
alert("要打印該表,您必須安裝 Excel 電子表格軟件,同時浏覽器須使用 ActiveX 控件並允許執行。");
return "";
}
xls.visible = true; // 設置 Excel 可見
var xlBook = xls.Workbooks.Add;
var xlsheet = xlBook.Worksheets(1);
// 合併第一行 1~7 列並寫入標題
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.Cells(2,1).Value = "卡號";
xlsheet.Cells(2,2).Value = "密碼";
xlsheet.Cells(2,3).Value = "計費方式";
xlsheet.Cells(2,4).Value = "有效天數";
xlsheet.Cells(2,5).Value = "金額";
xlsheet.Cells(2,6).Value = "所屬服務項目";
xlsheet.Cells(2,7).Value = "發卡時間";
// 把 HTML table 的內容逐格寫入 Excel
var oTable = document.all['fors:data'];
var rowNum = oTable.rows.length;
for(i = 2; i <= rowNum; i++){
for (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)).Borders(3).Weight = 2; // 左
xlsheet.Range(xlsheet.Cells(2,1), xlsheet.Cells(rowNum+1,7)).Borders(4).Weight = 2; // 右
xlsheet.Range(xlsheet.Cells(2,1), xlsheet.Cells(rowNum+1,7)).Borders(1).Weight = 2; // 上
xlsheet.Range(xlsheet.Cells(2,1), xlsheet.Cells(rowNum+1,7)).Borders(2).Weight = 2; // 下
xls.UserControl = true; // 交由用戶控制,不可省略
xls = null; xlBook = null; xlsheet = null;
}
在頁面上放置一個按鈕觸發 MakeExcel(),並用一個 id 為 fors:data 的 table 存放待導出的數據即可。點擊「生成 excel 文件」按鈕,腳本便會遍歷該表格的所有行與列,將內容原封不動地搬遷到 Excel 中,同時套用標題合併、字體、边框等樣式。
值得一提的是,這種方案依賴於 IE 的 ActiveX 控件,因此僅適用於支持 ActiveX 的浏覽器環境。在現代前端開發中,若追求跨平台兼容,可考慮 SheetJS 等純 JS 方案作為替代。