ASP 如何讀取 Word 檔案內容並顯示於網頁
一般而言 , 在 ASP 或 ASP.Net 中透過 CreateObject 建構函數建立 Word 物件
會有安全性及使用權限上的問題 , 因此若 虛擬目錄 不使用 整合 Windows 驗證
將無法存取 Word doc 檔 ,更不用說虛擬目錄以外的目錄 , 好比說 C:\ 根目錄下的 Word 檔。
底下介紹個方式,給大家參考看看:
l 使用 VB6
n 建立專案,選擇 ActiveX DLL
n 將專案的 Name屬性設定成 Ax,Class 的 Name 屬性設為 Word
n 編輯程式碼如下 :
n
|
Public Function GetDocContent(strFile As String) As String
Dim wdObj As Object ' 宣告
Set wdObj = CreateObject("Word.Application") ' 個體化 Word 物件
With wdObj
.Documents.Open strFile ' 開啟 Word 檔
GetDocContent = .ActiveDocument.Content ' 讀出 Word 內容囉
' 底下關掉 Word 檔 , 釋放資源
On Error Resume Next
.ActiveDocument.Close
.ActiveWindow.Close
.Quit
End With
Set wdObj = Nothing
End Function
|
n 編譯 製成 DLL
Compiler 完成後請使用 RegSvr32.exe 將該 Dll 元件 "反註冊" , 如
RegSvr32 /u "路徑+檔名.dll"
RegSvr32.exe 工具使用 可參考:
<< 關於 ActiveX (OLE) 元件登錄註冊 >>
http://blog.blueshop.com.tw/hammerchou/archive/2006/04/06/20787.aspx
l 執行 DCOMCNFG.EXE -> [確定]

n COM+應用程式 -> 滑鼠右鍵 -> 新增 -> 應用程式

n [下一步] -> 建立空的應用程式
n 輸入應用程式名稱 -> 伺服應用程式 -> [下一步]

n 使用下列使用者 -> 使用者 -> 密碼 / 確認密碼 -> [下一步] -> [完成]
u 輸入 Administrator 及密碼

n AxWord -> 元件 -> 滑鼠右鍵 -> 新增 -> 元件 -> [下一步]

n [安裝新元件]

n 選取 先前用 VB6 編譯製成的 DLL

n [下一步] -> [完成]

l ASP Code 如下:
n
|
<%
' 宣告
Dim wd
' 建立先前寫的 DLL 物件 , 個體化
Set wd = Server.CreateObject("AX.Word")
' 執行 Dll 中的 GetDocContent 方法讀 Word 內容
Response.Write wd.GetDocContent("C:\1.doc")
%>
|
================================================================
以上方式是使用 VB6 ,將 Word 物件 作動 的部份 寫成 ActiveX Dll ,
在放到元件服務裡的 COM+ 中,並指定 Administrator 去執行,以避開安全性上的權限問題;
但倘若手邊沒有 VB6開發工具呢 ? 底下介紹 WSC 的方式 ,只要文字檔不需 VB6 囉 !
WSC ( Windows Script Component )
l 建立一新 文字檔
n 編輯程式碼如下 :
n
|
<?xml version="1.0"?>
<component>
<registration
description="PH ActiveX Word Windows Script Component"
progid="AxWsc.Word"
version="1.00"
classid="{5F644CD7-E1D4-4D54-A260-B4CCC2F540FC}">
</registration>
<public>
<method name="GetDocContent">
</method>
</public>
<script language="VBScript">
<![CDATA[
Function GetDocContent(strFile)
Dim wdObj
Set wdObj = CreateObject("Word.Application")
With wdObj
.Documents.Open strFile
GetDocContent = .ActiveDocument.Content
On Error Resume Next
.ActiveDocument.Close
.ActiveWindow.Close
.Quit
End With
Set wdObj = Nothing
End Function
]]>
</script>
</component>
|
n 存檔 命名為 AxWord.wsc ( 注意副檔名為 WSC )
n 選取檔案 -> 滑鼠右鍵 -> 註冊 -> 出現註冊 是否成功 的訊息 -> [確定]

n 選取檔案 -> 滑鼠右鍵 -> 建立型態程式庫
u ( 會產生一 ScriptLet.tlb 的 Type Library 檔案 )

n 之後如同 ActiveX Dll 安裝於元件服務中的動作
n 直到 [安裝新元件] 時,請選擇 ScriptLet.tlb 檔案
n 完成後畫面如下 :

l ASP Code 如下:
n
|
<%
' 宣告
Dim wd
' 建立先前寫的 DLL 物件 , 個體化
Set wd = Server.CreateObject("AxWsc.Word")
' 執行 Dll 中的 GetDocContent 方法讀 Word 內容
Response.Write wd.GetDocContent("C:\1.doc")
%>
|