日期:2012-03-31  浏览次数:20897 次

随着人们对数据库及动态HTML (DHTML)的应用和对XML的兴趣的增加,所以在商业网站的数据中使用动态内容变得越来越普遍。这里我们就成功运用了一则最新的技巧——用ASP创建 Word 文件,我想您看后肯定会受到很大的启发。
原文出处:http://www.asptoday.com/articles/19990825.htm

   背景

   BuildDoc.asp是一个ASP文件,它读入一个网页表单的输出,并创建一个Microsoft Word文件作为输出, 其中包含根据表单内数据改变产生的一个表格。表单内容不再局限于静态信息。也就是说, 表单中所显示的内容可能随着用户的交互作用而改变。




  
   BuildDoc所满足的商业需求是:根据销售人员网页列表变化的记录,建立表单信件。只有被销售人员修改过的数据才被发送到Word, 在那里这些数据被格式化到表格中。

   BuildDoc读入表单上的所有信息,识别被改变的行,然后用被改变的行中包含的信息来创建一个 Microsoft Word文件。BuildDoc使用一个模板文件(buildDoc.dot),其中包含地址头和一些预先格式化的文本。然后向文件中写入一个表格,其中的每一行都对应与网页表单中被修改过的一行。




  
   怎么做?

   开始时,将所有的网页表单域读入接收网页的隐含表单域中。在下面的源代码中,请注意在Body标记中对“onLoad”的调用。它调用buildDoc VB脚本子程序,向它传递3个参数:页面中表单的内容(所有的隐含域)、Word模板文件的位置、从输入表单中收到的行数。读所有的输入表单域,然后当页面装载后调用buildDoc子程序。为了简短起见,这里假定所有变量在使用之前都已被声明:

   buildDoc.asp中装载输入表单域的代码如下:


〈!DOCTYPE HTML PUBLIC "-//W3C/DTD HTML 3.2 Final//EN">
〈HEAD>
〈TITLE>Build Document〈/TITLE>
〈META HTTP-EQUIV="Refresh" CONTENT="30;URL='orderForm.asp'">
〈/HEAD>
〈%
dotLocation="'servernamedirectory heTemplate.dot'"
intRowCount = Request.Form("rowCount") 'initialize a row counter
%>
〈BODY Language="VBScript" onLoad="buildDoc document.theForm,
〈%=dotLocation%>,intRowCount>
〈FORM NAME="theForm">
〈%
itemCount = 0 'set field counter to zero
For Each Item in Request.Form 'count up the form fields
itemCount = itemCount + 1 'using For..Next loop
%>
〈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>
〈/HTML>
   用下面例子中的代码来创建一个Word 文件对象。请注意在Internet Explorer 4+中,要将浏览器的安全性设置为Low或 Custom,以能使应用程序运行成功。


〈%
Set objWordDoc = CreateObject("Word.Document")
ObjWordDoc.Application.Documents.Add theTemplate, False
ObjWordDoc.Application.Visible=True
%>
   调整数组的维数使它与网页表单所包含的行数相同。这时,将Y轴设为4个常量,这是输出文件中所需要 的栏数。X轴包含从表单中接收的行数。

〈% Redim Preserve theArray(4,intTableRows) %>

   现在开始检查所有的表单行。在所有输入的网页表单域中循环,收集每个表单域名及其相应的值。逐个检查以决定将其放入哪个数列元素内,然后将其放入。以下举例代码中的SELECT CASE命令很重要,这决定表单域属于哪一列。为了方便,使用不确定编码的CASE选择。


〈%
For intCount = 0 to frmData.fieldCount.value
strOkay = "Y"
strSearch = frmData.elements(intCount).name 'load the field name
strValue = frmData.elements(intCount).value 'load the field value
strPosition = Instr(1,strSearch,"_") 'get pos val of "_"
intStringLen=strPosition-1
If intStrLen > 0 Then
strLeft = Left(strSearch,intStringLen)
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 = strRight
If strOkay 〈> "N" Then
TheArray(intArrayY, intArrayX) = strValue
End If
End If
Next
%>
   现在开始创建文件。对于激活的文件,用变量rngCurrent设置Microsoft Word文件对象RANGE(为了防止用户打开另一个文件),通过指定表格的位置( rngCurrent)以及行、列的数目来确定其大小。


〈%
Set rngCurrent = objWordDoc.Application.ActiveDocument.Content
Set tabCurrent = ObjWordDoc.Application.ActiveDocument.Tables.Add
rngCurrent