在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; WIDTH: 77.46%; BORDER-BOTTOM: 1 26px"
size="71"> <input style="BORDER-RIGHT: #999999 1px solid; BORDER-TOP: #999999 1px solid; FONT-SIZE: 15; BORDER-LEFT: #999999 1px solid; 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的安全性設置,否則將無效.