萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

ASP/VBScript 動態生成 Word 文檔:基於 Word.Document COM 組件的服務端方案

方案架構

利用服務端安裝的 Microsoft Word COM 組件 (Word.Document),通過 VBScript 操作 Word 對象模型,將表單數據填充到模板文檔並生成新文件。適用於內網、受控環境,不建議用於公網高併發場景(Word 進程資源重、穩定性差)。

核心流程

  1. 前端表單提交數據到 creatdoc.asp。
  2. 頁面 onLoad 觸發 VBScript 子程序 creatdoc,傳入表單數據、模板路徑、行數。
  3. 腳本創建 Word.Document 對象,基於模板創建新文檔。
  4. 解析表單隱藏域,按命名規則 (SKU_1, description_1 等) 組織二維數組。
  5. 在文檔中創建表格,逐行填充數據,設置格式(貨幣、對齊)。
  6. 添加固定尾部文本,顯示 Word 窗口供用戶保存/打印。

關鍵代碼片段

1. 前端表單與數據收集 (creatdoc.asp)

<body Language="VBScript" onLoad="creatdoc document.theForm, '<%=dotLocation%>', <%=intRowCount%>">
<FORM NAME="theForm">
<%
    itemCount = 0
    For Each Item in Request.Form
        itemCount = itemCount + 1
%>
    <INPUT TYPE="hidden" NAME="<%=Item%>" VALUE="<%=Request(Item)%>">
<% Next %>
    <INPUT TYPE="hidden" NAME="numbRows" VALUE="<%=intRowCount%>">
    <INPUT TYPE="hidden" NAME="fieldCount" VALUE="<%=itemCount%>">
</FORM>
</body>

2. 創建 Word 實例並加載模板

<%
Set objWordDoc = CreateObject("Word.Document")
ObjWordDoc.Application.Documents.Add theTemplate, False
ObjWordDoc.Application.Visible = True  ' 顯示 Word 窗口
%>

安全提示:IE 需將站點加入「受信任站點」,並設置安全級別為「低」或「自定義」啟用「初始化並腳本不安全的 ActiveX 控件」。

3. 解析表單數據構建二維數組

<%
Redim Preserve theArray(4, intTableRows)  ' 4列 x N行

For intCount = 0 To frmData.fieldCount.Value
    strOkay = "Y"
    strSearch = frmData.elements(intCount).Name
    strValue = frmData.elements(intCount).Value
    strPosition = InStr(1, strSearch, "_")
    
    If strPosition > 0 Then
        intStringLen = strPosition - 1
        strLeft = Left(strSearch, intStringLen)      ' 列前綴: SKU, description, price, quantity
        strRight = Right(strSearch, Len(strSearch) - Len(strLeft) - 1)  ' 行號
        
        Select Case strLeft
            Case "SKU"         : intArrayY = 0
            Case "description" : intArrayY = 1
            Case "price"       : intArrayY = 2
            Case "quantity"    : intArrayY = 3
        End Select
        
        IntArrayX = CInt(strRight)
        If strOkay <> "N" Then
            TheArray(intArrayY, IntArrayX) = strValue
        End If
    End If
Next
%>

4. 創建表格並填充數據

<%
Set rngCurrent = objWordDoc.Application.ActiveDocument.Content
Set tabCurrent = ObjWordDoc.Application.ActiveDocument.Tables.Add(rngCurrent, intNumRows, 4)

tabRow = 1
For j = 1 To intTableRows
    ' 移除邊框
    ObjWordDoc.Application.ActiveDocument.Tables(1).Rows(tabRow).Borders.Enable = False
    
    ' 填充四列
    ObjWordDoc.Application.ActiveDocument.Tables(1).Rows(tabRow).Cells(1).Range.InsertAfter TheArray(0, j)  ' SKU
    ObjWordDoc.Application.ActiveDocument.Tables(1).Rows(tabRow).Cells(2).Range.InsertAfter TheArray(1, j)  ' Description
    ObjWordDoc.Application.ActiveDocument.Tables(1).Rows(tabRow).Cells(3).Range.InsertAfter FormatCurrency(TheArray(2, j))  ' Price
    ObjWordDoc.Application.ActiveDocument.Tables(1).Rows(tabRow).Cells(4).Range.InsertAfter TheArray(3, j) & Chr(10)  ' Quantity + 換行
    
    ' 價格列右對齊
    ObjWordDoc.Application.ActiveDocument.Tables(1).Rows(tabRow).Cells(3).Range.ParagraphFormat.Alignment = 2  ' wdAlignParagraphRight
    
    tabRow = tabRow + 1
Next
%>

5. 添加固定尾部內容

<%
ObjWordDoc.Application.ActiveDocument.Paragraphs.Add.Range.InsertAfter "Thank you for shopping at Acme Co., and please come again!"
ObjWordDoc.Application.ActiveDocument.Paragraphs.Add.Range.InsertAfter ""
ObjWordDoc.Application.ActiveDocument.Paragraphs.Add.Range.InsertAfter ""
ObjWordDoc.Application.ActiveDocument.Paragraphs.Add.Range.InsertAfter "Regards,"
ObjWordDoc.Application.ActiveDocument.Paragraphs.Add.Range.InsertAfter ""
ObjWordDoc.Application.ActiveDocument.Paragraphs.Add.Range.InsertAfter "Daryl B. Morticum"
ObjWordDoc.Application.ActiveDocument.Paragraphs.Add.Range.InsertAfter "Sales Associate"
End Sub
%>

局限性與現代替代方案

問題現代替代方案
依賴服務端安裝 Word,授權成本高開源庫:python-docx (Python), docx4j (Java), OpenXML SDK (.NET)
COM 組件併發性差,易導致 Word 進程殭屍無併發限制,純代碼操作 XML
僅限 Windows Server + IE 客戶端跨平台,瀏覽器無關
安全風險(ActiveX、宏病毒)純數據生成,無宏風險
格式控制依賴 Word 對象模型,代碼冗長聲明式模板(Jinja2 + docxtpl、Mail Merge)

Python 現代化示例 (python-docx)

from docx import Document
from docx.shared import Pt, Cm

doc = Document("template.docx")
table = doc.add_table(rows=1, cols=4)
hdr = table.rows[0].cells
hdr[0].text, hdr[1].text, hdr[2].text, hdr[3].text = "SKU", "Description", "Price", "Qty"

for row_data in data_rows:
    row = table.add_row().cells
    row[0].text = row_data['sku']
    row[1].text = row_data['desc']
    row[2].text = f"${row_data['price']:.2f}"
    row[2].paragraphs[0].alignment = 2  # 右對齊
    row[3].text = str(row_data['qty'])

doc.add_paragraph("Thank you for shopping...")
doc.save("output.docx")

總結

經典 ASP + Word COM 方案在特定歷史環境下解決了服務端生成 Word 需求,但架構脆弱、難維護。現代項目應採用純代碼庫(python-docx、OpenXML 等)或報表服務,實現跨平台、高併發、易維護的文檔生成。

copyright © 萬盛學電腦網 all rights reserved