HOW TO:使用 ASP 產生 RTF 格式文件以串流至 Microsoft Word

文章翻譯 文章翻譯
文章編號: 270906 - 檢視此文章適用的產品。
本文曾發行於 CHT270906
全部展開 | 全部摺疊

結論

本文將告訴您如何使用 ASP 指令碼產生 RTF 格式的檔案,然後將這些檔案串流至 Microsoft Word。此技術為執行階段的文件建立作業,提供另一種方式的 Microsoft Word 伺服器端自動化。

其他相關資訊

使用 ASP 伺服器端自動化來產生 Word 文件有其缺點:
  • 效能 - Microsoft Word 是一種跨處理序 (Out-Of-Process) 的自動化伺服器;跨處理序的呼叫需要較長的執行時間。

  • 延展性 - 做為自動化伺服器,Microsoft Word 會有很龐大的負荷,因為必須載入 Winword.exe 才能讓您獲得 Word 豐富的物件模型益處。
從頭開始產生文件而不使用 Word 物件模型,可以讓 ASP 應用程式更容易調整,同時也會增加效能。下列範例使用此方法,示範如何使用 FileSystemObject,以建立可在瀏覽器用戶端的 Microsoft Word 中直譯的 RTF 檔。

第一個範例顯示如何使用 ASP 建立 RTF 文件,該文件包含頁首與頁尾、包含表格,且整份文件的文字還使用各種不同的字型樣式與顏色。第一個範例使用 ADO 來存取 Access 範例資料庫 Northwind 中的資料,建立一份 90 多頁的文件。

第二個範例示範如何建立類似 Word 合併列印的 RTF 文件。產生的文件會包含頁首與頁尾、各種不同的段落格式與分頁符號,並且整份文件還使用各種不同的字型樣式與類型。此範例也使用 ADO 來存取 Northwind 資料庫中的資料,建立了一份 170 多頁的文件。

注意 RTF 格式規格是用於產生與 RTF 相容的文字檔案的公開規格。您可以使用下列 Microsoft Developer Network (MSDN) 網站的規格文件做為資源,協助您建立自己的 RTF 檔案。然而,規格是以「現狀」提供,而且 Microsoft 技術支援服務並不提供相關支援。如需 RTF 規格的最新版本,請參閱下列 MSDN 網站:
RTF 格式規格 1.6 (英文)
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnrtfspec/html/rtfspec.asp

ASP 範例 1

以下 ASP 範例將示範如何建立 90 多頁的 RTF 文件,且該文件包含計算數字的報告。

注意 此程式碼範例中的 sConn 變數含有指向 Northwind 資料庫的路徑。請確認此範例中的路徑是否適合您的 Office 安裝。您也必須為包含此 ASP 的資料夾設定寫入存取權,才能建立文件。在 Windows NT 網域下,此存取權應該要限制給特定的個人,但如果是匿名存取,則可以套用至 Everyone
<%@ 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 網域下,此存取權應該要限制給特定的個人,但如果是匿名存取,則可以套用至 Everyone
<%@ 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 & """>"

%> 
				

?考

如需詳細資訊,請按一下下面的文件編號,檢視「Microsoft 知識庫」中的文件:
257757 Office 伺服器端自動化的考量因素
193998 HOWTO:在 ASP 中讀取與顯示二進位資料
266263 BUG: Word 2000 and Excel 2000 Display ASP Source When Using MIME Type to Stream Data
247318 BUG: Word 2000 and Excel 2000 Do Not Redirect Correctly When Using Response.Redirect

屬性

文章編號: 270906 - 上次校閱: 2006年8月22日 - 版次: 7.0
這篇文章中的資訊適用於:
  • Microsoft Office Word 2003
  • Microsoft Word 2000 Standard Edition
  • Microsoft Word 97 Standard Edition
  • Microsoft Active Server Pages 4.0
關鍵字:?
kbautomation kbfso kbhowto kbprogramming KB270906
Microsoft及(或)其供應商不就任何在本伺服器上發表的文字資料及其相關圖表資訊的恰當性作任何承諾。所有文字資料及其相關圖表均以「現狀」供應,不負任何擔保責任。Microsoft及(或)其供應商謹此聲明,不負任何對與此資訊有關之擔保責任,包括關於適售性、適用於某一特定用途、權利或不侵權的明示或默示擔保責任。Microsoft及(或)其供應商無論如何不對因或與使用本伺服器上資訊或與資訊的實行有關而引起的契約、過失或其他侵權行為之訴訟中的特別的、間接的、衍生性的損害或任何因使用而喪失所導致的之損害、資料或利潤負任何責任。

提供意見

 

Contact us for more help

Contact us for more help
Connect with Answer Desk for expert help.
Get more support from smallbusiness.support.microsoft.com