在伺服器端啟動 Excel.Application、開啟範本 (.xlt)、填入資料、設定列印區域、觸發列印、關閉 Excel。全程無使用者介面,適用於批次報表自動列印。
<%
Option Explicit
Response.Buffer = True
Response.ContentType = "text/html; charset=utf-8"
Dim xlApp, xlBook, xlSheet, conn, rs, sql, i, templatePath, printerName
templatePath = Server.MapPath("/templates/report_template.xlt")
printerName = "\\PrintServer\HP_LaserJet_4000" ' 網路印表機共享名
On Error Resume Next
Set xlApp = Server.CreateObject("Excel.Application")
If Err.Number <> 0 Then
Response.Write "Excel 啟動失敗: " & Err.Description
Response.End
End If
On Error GoTo 0
xlApp.DisplayAlerts = False
xlApp.Visible = False
xlApp.ActivePrinter = printerName
Set xlBook = xlApp.Workbooks.Open(templatePath)
Set xlSheet = xlBook.ActiveSheet
' 連線資料庫
Set conn = Server.CreateObject("ADODB.Connection")
conn.Open "Provider=SQLOLEDB;Data Source=.;Initial Catalog=ERP;UID=sa;PWD=xxx"
sql = "SELECT OrderID, CustomerName, OrderDate, TotalAmount FROM Orders WHERE Status='Confirmed' ORDER BY OrderDate DESC"
Set rs = conn.Execute(sql)
' 填寫資料 (假設範本第 5 列起為資料區)
i = 5
Do Until rs.EOF
xlSheet.Cells(i, 1).Value = rs("OrderID")
xlSheet.Cells(i, 2).Value = rs("CustomerName")
xlSheet.Cells(i, 3).Value = rs("OrderDate")
xlSheet.Cells(i, 4).Value = rs("TotalAmount")
i = i + 1
rs.MoveNext
Loop
' 設定列印區域並列印
xlSheet.PageSetup.PrintArea = "$A$4:$D$" & (i - 1)
xlBook.PrintOut Copies:=1, Collate:=True, ActivePrinter:=printerName
' 清理
rs.Close: Set rs = Nothing
conn.Close: Set conn = Nothing
xlBook.Close False
Set xlBook = Nothing
xlApp.Quit
Set xlApp = Nothing
Response.Write "報表列印已送入佇列 (" & (i-5) & " 筆資料)。"
%>
DCOMCNFG (Win+R → dcomcnfg)。iisreset)。| 現象 | 原因 | 對策 |
|---|---|---|
| Excel 進程殘留 (殭屍) | 錯誤發生中斷、未 Quit、未 Release COM | 全程 On Error Resume Next + 結構化清理、Class_Terminate 雙重保險、排程每日清理 EXCEL.EXE |
| 列印無反應/錯誤 1004 | 印表機名稱錯誤、驅動程式不相容、無桌面互動 | 確認 ActivePrinter 字串完全正確、印表機驅動安裝於伺服器、身分識別=互動使用者 |
| 中文亂碼/字型缺失 | 伺服器缺字型、範本字型非標準 | 範本僅用標準字型 (微軟正黑體/新細明體)、確保伺服器安裝相同字型 |
| 並發列印卡死 | Excel 單執行緒、COM 單元件 | 改用列印佇列服務 (資料庫寫入列印任務表,單一背景服務輪詢列印) |