当前位置: 首页 > 文章分类 > 编程开发 > ASP > 文章页面

文章正文:

使用ASP生成RTF文档以将数据流传送到Microsoft Word

作者:佚名 时间:2006-10-7 13:51:29 来源:网络

概要
本文阐述如何使用 ASP 脚本生成 RTF 文件,然后将这些文件的数据流传送到 Microsoft Word。该技术为用于运行时文档生成的 Microsoft Word 服务器端自动执行提供了一种替代方法。
更多信息
使用 ASP 服务器端自动执行生成 Word 文档存在一些缺点:
性能:Microsoft Word 是进程外自动化服务器,进程外调用执行的时间较长。

可扩展性:作为自动化服务器,Microsoft Word 需要大量开销;因为必须加载 Winword.exe 文件,才能获得 Word 的丰富对象模型的好处。
通过从一开始就生成文档并且不使用 Word 对象模型,可以增强 ASP 应用程序的可扩展性,而且还可以提高性能。下面的示例通过使用此方法,演示了如何使用 FileSystemObject 创建可在浏览器客户端的 Microsoft Word 中解析的 RTF 文件。

第一个示例显示了如何使用 ASP 创建一个 RTF 文档:包含页眉和页脚、包含表并在整个文档中使用不同的文本字体样式和颜色。该示例使用 ADO 访问示例 Northwind Access 数据库的数据,以创建一个 90 多页的文档。

第二个示例演示了如何创建类似于 Word 邮件合并的 RTF 文档。所产生的文档包含页眉和页脚、各种段落格式和分页符,并在整个文档中使用不同的字体样式和类型。该示例也使用 ADO 访问 Northwind 数据库的数据,以创建一个 170 多页的文档。

注意:RTF 规范是生成 RTF 兼容文本文件的公用规范。可以使用下面 Microsoft Developer Network (MSDN) Web 站点的文档规范作为资源,来帮助您创建自己的 RTF 文件。不过,该规范“按原样”提供,并且未得到 Microsoft 技术支持部门的支持。有关 RTF 规范的最新版本,请参见下面的 MSDN Web 站点:
Rich Text Format (RTF) Specification 1.6(RTF 规范 1.6)
http://msdn.microsoft.com/library/default.asp?URL=/library/specs/rtfspec.htm

ASP 示例 1
下面的 ASP 演示了如何创建一个包含计算数据报表的 90 多页的 RTF 文档。

注意:此代码示例中的变量 sConn 包含 Northwind 数据库的路径。请确认所提供的路径适用于您的 Office 安装。此外,还需要提供对包含 ASP 文件夹的写访问权,才能创建文档。此访问权应限于 Windows NT 域中的特定用户,但对于匿名访问可适用于每个用户。
〈%@ Language=VBScript %〉
〈%

   Dim sRTF, sFileName, sConn
   sConn = “c:\program files\microsoft office\office\samples\northwind.mdb“

   Response.Buffer = True

   ’Create the file for the RTF
   Dim fso, MyFile
   Set fso = CreateObject(“Scripting.FileSystemObject“)
   sFileName = “sample1.doc“
   Set MyFile = fso.CreateTextFile(Server.MapPath(“.“) & “\“ & _
                                   sFileName, True)

   MyFile.WriteLine(“{\rtf1“)

   ’Write the color table (for use in background and foreground colors)
   sRTF = “{\colortbl;\red0\green0\blue0;\red0\green0\blue255;“ & _
          “\red0\green255\blue255;\red0\green255\blue0;“ & _
          “\red255\green0\blue255;\red255\green0\blue0;“ & _
          “\red255\green255\blue0;\red255\green255\blue255;}“
   MyFile.WriteLine(sRTF)

   ’Write the title and author for the document properties
   MyFile.WriteLine(“{\info{\title Sample RTF Document}“ & _
                    “{\author Microsoft Developer Support}}“)

   ’Write the page header and footer
   MyFile.WriteLine(“{\header\pard\qc{\fs50 “ & _
                    “ASP-Generated RTF\par}{\fs18\chdate\par}\par\par}“)
   MyFile.WriteLine(“{\footer\pard\qc\brdrt\brdrs\brdrw10\brsp100“ & _
                    “\fs18 Page “ & _
                    “{\field{\*\fldinst PAGE}{\fldrslt 1}} of “ & _
                    “{\field{\*\fldinst NUMPAGES}{\fldrslt 1}} \par}“)

   ’Write a sentence in the first paragraph of the document
   MyFile.WriteLine(“\par\fs24\cf2 This is a sample \b RTF \b0 “ & _
                    “document created with ASP.\cf0“)

   ’Connect to the database in read-only mode
   Dim conn, rs
   Set conn = Server.CreateObject(“ADODB.Connection“)
   conn.Provider = “Microsoft.Jet.OLEDB.4.0“
   conn.Mode = 1    ’adModeRead=1
   conn.Open sConn

   ’Execute a query that returns ID, Product name and amount of sale
   Set rs = Server.CreateObject(“ADODB.Recordset“)
   rs.Open “SELECT [Order Details].OrderID AS ID, “ & _
           “Products.ProductName AS Name, “ & _
           “[Order Details].[UnitPrice]*[Quantity] AS Amount “ & _
           “FROM Products INNER JOIN [Order Details] ON “ & _
           “Products.ProductID = [Order Details].ProductID “ & _
           “ORDER BY [Order Details].OrderID“, conn, 3   ’adOpenStatic = 3

   MyFile.WriteLine(“{“) ’Start table
   MyFile.WriteLine(“\par\par\fs24“)

   ’Write the table header row (appears at top of table on each page)
   sRTF = “\trowd\trhdr\trgaph30\trleft0\trrh262“ & _
          “\cellx2000\cellx7000\cellx9000“ & _
          “\pard\intbl\qc\b\i\ul Order ID \ul0\i0\b0\par\cell“ & _
          “\pard\intbl\ql\b\i\ul Product \ul0\i0\b0\par\cell“ & _
          “\pard\intbl\qr\ul\b\i Amount \ul0\i0\b0\par\cell“ & _
          “\pard\intbl\row“
   MyFile.WriteLine(sRTF)

   dim LastID
   dim CurID
   dim CurTotal
   dim bFirstRow

   bFirstRow=true

   do while not (rs.eof)

     if LastID〈〉rs(“ID“).Value and not(bFirstRow)  Then

        ’Starting on a row for a different id, so add the last total and
        ’then a blank row
        sRTF = “\trowd\trgaph30\trleft0\trrh262“ & _
               “\cellx2000\cellx7000\clbrdrb\brdrdb\cellx9000“ & _
               “\pard\intbl\cell\pard\intbl\cell\pard\intbl\qr\b “ & _
               FormatCurrency(CurTotal, 0, False, False, True) & _
               “\b0\cell\pard\intbl\row“ & _
               “\trowd\trgaph30\trleft0\trrh262“ & _
               “\cellx2000\cellx7000\cellx9000“ & _
               “\pard\intbl\cell\pard\intbl\cell\pard\intbl\cell“ & _
               “\pard\intbl\row“
        MyFile.WriteLine(sRTF)

        CurID = rs(“ID“).Value
        CurTotal = 0
     elseif bFirstRow then
        CurID = rs(“ID“).Value
     else
        CurID = ““
     end if

     ’Add a new row with the ID, the Product name and the amount
     ’Note: Amounts over 1000 are formatted with red.
     sRTF = “\trowd\trgaph30\trleft0\trrh262“ & _
            “\cellx2000\cellx7000\cellx9000“ & _
            “\pard\intbl\qc “ & CurID & “\cell“ & _
            “\pard\intbl\ql “ & rs(“Name“).Value & “\cell“
     If rs(“Amount“).Value 〉1000 Then
        sRTF = sRTF & “\pard\intbl\qr\cf6 “ & _
               FormatNumber(rs(“Amount“).Value, 0, False, False, True) & _
               “\cf0\cell\pard\intbl\row“
     else
        sRTF = sRTF & “\pard\intbl\qr “ & _
               FormatNumber(rs(“Amount“).Value, 0, False, False, True) & _
               “\cell\pard\intbl\row“
     end if

     MyFile.WriteLine(sRTF)

     LastID = rs(“ID“).Value
     CurTotal = CurTotal + rs(“Amount“).Value
     rs.MoveNext
     bFirstRow=false

   loop

   MyFile.WriteLine(“}“) ’End Table

   ’Add a page break and then a new paragraph
   MyFile.WriteLine(“\par \page“)
   MyFile.WriteLine(“\pard\fs18\cf2\qc “ & _
                    “This sample provided by Microsoft Developer Support.“)

   ’Close the recordset and database
   rs.Close
   conn.Close
   Set rs = Nothing
   Set conn = Nothing

   ’close the RTF string and file
   MyFile.WriteLine(“}“)
   MyFile.Close

   Response.Write _
       “〈META HTTP-EQUIV=““REFRESH““ Content=““0;URL=“ & sFileName & “““〉“
%〉

ASP 示例 2
下面的 ASP 演示了如何模拟 Word 邮件合并或套用信函。170 多页文档中的每一页都从 ADO 记录集中的一个记录生成。

注意:此代码示例中的变量 sConn 包含 Northwind 数据库的路径。请确认所提供的路径适用于您的 Office 安装。此外,还需要提供对包含 ASP 文件夹的写访问权,才能创建文档。此访问权应限于 NT 域中的特定用户,但对于匿名访问可适用于每个用户。
〈%@ Language=VBScript %〉
〈%
   Dim sRTF, sConn
   sConn = “c:\program files\microsoft office\office\samples\northwind.mdb“

   Response.Buffer = True

   ’Create the file for the RTF
   Dim fso, MyFile, sFileName
   Set fso = CreateObject(“Scripting.FileSystemObject“)
   sFileName = “sample2.doc“
   Set MyFile = fso.CreateTextFile(Server.MapPath(“.“) & “\“ & sFileName, True)

   MyFile.WriteLine(“{\rtf1“)

   ’Write the font table
   sRTF = “{\fonttbl {\f0\froman\fcharset0 Times New Roman;}“ & “{\f1\fswiss\fcharset0 Arial;}“ & _
          “{\f2\fmodern\fcharset0 Courier New;}}“
   MyFile.WriteLine sRTF

   ’Write the title and author for the document properties
   MyFile.WriteLine(“{\info{\title Sample RTF Document}“ & “{\author Microsoft Developer Support}}“)

   ’Write the document header and footer
   MyFile.WriteLine(“{\header\pard\qc\brdrb\brdrs\brdrw10\brsp100“ & “{\fs50 Northwind Traders} \par}“)
   MyFile.WriteLine(“{\footer\pard\qc\brdrt\brdrs\brdrw10\brsp100“ & “{\fs18 Questions?\par Call (111)-222-3333, “ & _
                    “ Monday-Friday between 8:00 am and 5:00 pm} \par}“)

   ’Connect to the database in read-only mode
   Dim conn, rs
   Set conn = Server.CreateObject(“ADODB.Connection“)
   conn.Provider = “Microsoft.Jet.OLEDB.4.0“
   conn.Mode = 1    ’adModeRead=1
   conn.Open sConn

   ’Execute a query that returns ID, Product name and amount of sale
   Set rs = Server.CreateObject(“ADODB.Recordset“)
   rs.Open “SELECT Orders.ShippedDate, Orders.ShipVia, “ & _
           “Orders.OrderDate, Orders.OrderID, “ & _
           “Customers.ContactName FROM Customers INNER JOIN Orders ON “ & _
           “Customers.CustomerID = “ & _
           “Orders.CustomerID WHERE (((Orders.ShippedDate) Between “ & _
           “#1/1/1998# And #3/31/98#))“,conn,3  ’adOpenStatic = 3

   Do While Not (rs.eof)

     ’Write the “body“ of the form letter

     MyFile.WriteLine   “\fs26\f1“   ’Default font

     MyFile.WriteLine   “\pard“
     MyFile.WriteLine   “\par\par\par\par“
     MyFile.WriteLine   “\par RE: Order #“ & rs.Fields(“OrderID“).Value
     MyFile.WriteLine   “\par“
     MyFile.WriteLine   “\par“
     MyFile.WriteLine   “\par “ & rs.Fields(“ContactName“).Value & “, “
     MyFile.WriteLine   “\par“
     MyFile.WriteLine   “\par Thank you for your order on “ & _
                        rs.Fields(“ShippedDate“).Value & _
                        “. Your order has been shipped: “
     MyFile.WriteLine   “\par“
     MyFile.WriteLine   “\par“

     MyFile.WriteLine   “\pard \li720 {\f2“
     MyFile.WriteLine   “\par \b Order Number \b0 \tab “ & _
                        rs.Fields(“OrderID“).Value
     MyFile.WriteLine   “\par \b Shipped By \b0 \tab “ & _
                        rs.Fields(“ShipVia“).Value
     MyFile.WriteLine   “\par \b Shipped On \b0 \tab “ & _
                        rs.Fields(“ShippedDate“).Value
     MyFile.WriteLine   “\par}“

     MyFile.WriteLine   “\pard“
     MyFile.WriteLine   “\par“
     MyFile.WriteLine   “\par Northwind Traders is committed to “ & _
                        “bringing you products of the “ & _
                        “highest quality from all over the world. If “ & _
                        “at any time you are not completely satisfied “ & _
                        “with any of our products, you may “ & _
                        “return them to us for a full refund.“
     MyFile.WriteLine   “\par“

     MyFile.WriteLine   “\pard {\fs18 \qc \i“
     MyFile.WriteLine   “\par Thank you for choosing Northwind Traders!“
     MyFile.WriteLine   “\par}“

     rs.MoveNext

     ’Add a page break and then a new paragraph
     If Not(rs.eof) Then MyFile.WriteLine(“\pard \page“)

   Loop

   ’Close the recordset and database
   rs.Close
   conn.Close
   Set rs = Nothing
   Set conn = Nothing

   ’close the RTF string and file
   MyFile.WriteLine(“}“)
   MyFile.Close

   Response.Write _
        “〈META HTTP-EQUIV=““REFRESH““ Content=““0;URL=“ & sFileName & “““〉“
%〉

[责任编辑:]
评论列表:
暂无评论
登录名: 密码:匿名发表(无需注册)