ASP读取Word内容并显示于网页
最近看到在QQ邮箱中有直接把word文档显示成html的功能,虽然只能够读取文本的内容,也想弄来试一下,所以就有了本文:asp如何读取word文档内容并显示于网页。
下面是原载于強力鎯頭 の VB 部落的。
http://blog.blueshop.com.tw/hammerchou/archive/2006/11/03/44307.aspx
一般而言 , 在 ASP 或 ASP.Net 中透过 CreateObject 建构函数建立 Word 对象
会有安全性及使用权限上的问题 , 因此若 虚拟目录 不使用 整合 Windows 验证
将无法存取 Word doc 檔 ,更不用说虚拟目录以外的目录 , 好比说 C:\ 根目录下的 Word 文件。
底下介绍个方式,给大家参考看看:
使用 VB6
建立项目,选择 ActiveX DLL
将项目的 Name属性设定成 Ax,Class 的 Name 属性设为 Word
编辑程序代码如下 :
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
编译 制成 DLL
Compiler 完成后请使用 RegSvr32.exe 将该 Dll 组件 "反注册" , 如
RegSvr32 /u "路径+文件名.dll"
RegSvr32.exe 工具使用 可参考:
<< 关于 ActiveX (OLE) 组件登录注册 >>
http://blog.blueshop.com.tw/hammerchou/archive/2006/04/06/20787.aspx
执行 DCOMCNFG.EXE -> [确定]
COM+应用程序 -> 鼠标右键 -> 新增 -> 应用程序
[下一步] -> 建立空的应用程序
输入应用程序名称 -> 伺服应用程序 -> [下一步]
使用下列使用者 -> 使用者 -> 密码 / 确认密码 -> [下一步] -> [完成]
输入 Administrator 及密码
AxWord -> 组件 -> 鼠标右键 -> 新增 -> 组件 -> [下一步]
[安装新组件]
选取 先前用 VB6 编译制成的 DLL
[下一步] -> [完成]
ASP Code 如下:
<%
' 声明
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 )
建立一新 文字文件
编辑程序代码如下 :
<?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>
存档 命名为 AxWord.wsc ( 注意扩展名为 WSC )
选取档案 -> 鼠标右键 -> 注册 -> 出现注册 是否成功 的讯息 -> [确定]
选取档案 -> 鼠标右键 -> 建立型态链接库
( 会产生一 ScriptLet.tlb 的 Type Library 档案 )
之后如同 ActiveX Dll 安装于组件服务中的动作
直到 [安装新组件] 时,请选择 ScriptLet.tlb 档案
完成后画面如下 :
ASP Code 如下:
<%
' 声明
Dim wd
' 建立先前写的 DLL 对象 , 个体化
Set wd = Server.CreateObject("AxWsc.Word")
' 执行 Dll 中的 GetDocContent 方法读 Word 内容
Response.Write wd.GetDocContent("C:\1.doc")
%>