web中,如何读取客户端Word内容并且显示在页面中?
我发现有2种方法,一种是直接在客户端操作,一种是把客户端的word上传到服务器端操作,这2种各有优缺点。
我现就举出客户端操作的例子
首先在.aspx中添加如下js代码
<script language='javascript'>
//默认word转化文件放于C:\下
var os__localPath = "C:\";
//保存的文件名
var os__localFile = "defaultFileWord.htm";
var os__xmlDom = new ActiveXObject("MSXML2.DOMDocument");
var os__xmlFSO ;
//保存数据到当前客户端(可以传入一个要保存的文件名).
function os_SaveToLocal()
{
var _saveAs = "";
if(arguments.length > 0)
_saveAs = arguments[0] + "";
else
_saveAs = os__localFile;
try
{
if(os__xmlFSO == null)
os__xmlFSO = new ActiveXObject("Scripting.FileSystemObject");
}
catch(e){window.alert(e);}
}
//Word转化为Html文件
function WorcChangeHtml()
{
var os_xmlFSO;
//获得上传控件对象
var objUpFile = window.document.Form1.updFile;
//获得客户端Word文件路径和文件
var UpFileValue = window.document.Form1.updFile.value;
if(os__xmlFSO == null)
os__xmlFSO = new ActiveXObject("Scripting.FileSystemObject");
try
{
if(window.document.Form1.updFile.value == "")
{
alert('请选择对应的Word文件');
objUpFile.focus();
}
else if(UpFileValue.indexOf(".doc") == -1)
{
alert('您选择的不是Word文件 rn请选择正确的Word文件');
objUpFile.focus();
}
else if(!os__xmlFSO.FileExists(objUpFile.value))
{
alert('对应的Word文件不存在');
objUpFile.focus();
}
else
{
var wdFormatHTML = 8;
var objWord = new ActiveXObject("Word.Application");
objWord.Application.Visible = false;
var objDoc = objWord.Documents.Open(UpFileValue);
objDoc.SaveAs(os__localPath+os__localFile, wdFormatHTML);
window.document.Form1.updFile.value = "";
objDoc.Close();
objWord.Quit();
var GetHtml = GetLine();
var iBeginIndex = GetHtml.indexOf("<body");
var iEndIndex = GetHtml.lastIndexOf("</body>");
GetHtml = GetHtml.substring(iBeginIndex,iEndIndex+7).replace("<body","<div");
GetHtml = GetHtml.replace("</body>","</div>");
//将转化后的值赋给页面控件txtIdea的值,我为了将Word值保存进数据库所以用<input type = "hidden" ..... 如果将Word内容显示可以考虑 window.document.Form1."你的显示控件ID".innerText = GetHtml;
window.document.Form1.txtIdea.value = GetHtml;
}
}
catch(e){window.alert(e);}
}
//读取文本文件
function GetLine()
{
var fso, txtfile, strValue;
var ForReading = 1, ForWriting = 2;
fso = new ActiveXObject("Scripting.FileSystemObject");
txtfile = fso.OpenTextFile(os__localPath+os__localFile, ForReading);
while(!txtfile.AtEndOfStream)
{
strValue = strValue + txtfile.ReadLine();
}
txtfile.Close();
return(strValue);
}
</script>
注意页面上需要添加以下2个控件和对应的客户端事件
<input id="updFile" type="file" style="BORDER-RIGHT: 1px solid; BORDER-TOP: 1px solid; BORDER-LEFT: 1px solid; WIDTH: 77.46%; BORDER-BOTTOM: 1px solid; HEIGHT: 26px"
size="71"> <input style="BORDER-RIGHT: #999999 1px solid; BORDER-TOP: #999999 1px solid; FONT-SIZE: 15pt; BORDER-LEFT: #999999 1px solid; WIDTH: 103px; BORDER-BOTTOM: #999999 1px solid; HEIGHT: 28px"
onclick="WorcChangeHtml()" runat="server" id="btnUpLoad" type="submit" value="导入" name="btnUpLoad">
<textarea style="WIDTH: 15.25%; HEIGHT: 23px" rows="50" cols="16" id="txtIdea"
runat="server">
其中txtIdea中的值就是客户端Word中的内容了,注意:需要调整IE的安全性设置,否则将无效.