開發平台:Visual Studio 2005 語言:C#
首先添加應用"Microsoft Word 11.0 Object library"的COM組件,從而來實現讀取word文檔的對象。
然後添加命名空間using System.Windows.Forms; //添加應用,添加System.Windows.Forms 的.NET組件
代碼實現:
object filepath = this.FileUpload1.PostedFile.FileName;//取檔案名稱
Word.Application WordApp = new Word.ApplicationClass();
object nullobj = System.Reflection.Missing.Value;
Word.Document doc = WordApp.Documents.Open(ref filepath, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj);
doc.ActiveWindow.Selection.WholeStory();//全部選擇word中的文檔
//doc.ActiveWindow.Selection.Copy();
//IDataObject data=Clipboard.GetDataObject();
//txtFileContent.Text=data.GetData(DataFormats.Text).ToString();
//有些以上的做法,通過copy的方式,得到剪貼簿的內容,這種做法取到的data為null根本不能達到效果,此時是因為word中的剪下板和系統剪下板並不一樣
this.txtFileContent.Text = doc.ActiveWindow.Selection.Text;//使網頁中的txtFileContent控制項的text等於選擇的文檔
doc.Close(ref nullobj, ref nullobj, ref nullobj);//關閉
WordApp.Quit(ref nullobj, ref nullobj, ref nullobj);//離開