在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
Word对象模型 (.Net Perspective) 本文主要针对在Visual Studio中使用C# 开发关于Word的应用程序 五大对象 Application :代表Microsoft Word应用程序本身 Document :代表一个Word文档 Selection :代表当前选中的区域(高亮),没有选中区域时代表光标点 Bookmarks :书签 Range :代表一块区域,与Selection类似,不过一般不可见
下面看一下Word的对象结构图:
OK,下面是对上述几大对象的基本特性的描述,让我们对它们有一些基本的认识。
l Application是Document和Selection的基类。通过Application的属性和方法,我们可以控制Word的大环境。
l Document代表一个Word文档,当你新建一个Word文档或者打开一个已有的Word文档,你将创建一个Document对象,该对象被加入到Words Documents Collection中。拥有焦点的Document称为ActiveDocument,可以通过Application对象的ActiveDocument属性获得当前文档对象
l Selection代表当前选中的区域,它通常是高亮显示的(例如,你要改变一段文字的字体,你首先得选 中这段文字,那么选中的这块区域就是当前文档的Selection对象所包含的区域)
l Range对象也代表文档中的一块区域,它具有以下特点
l Bookmark对象也代表一块区域,一般使用Bookmark来标记文档中的位置,它有如下特点
--------------------------------------------------------------------------------------------- 下面分别介绍5大对象: 1. The Application Object 通过Application对象,你可以访问Word的所有对象以及Collections。 参考更多:MSDN-Word2007-Application Object 1.1 Application对象的属性(只介绍部分,完整内容请参看MSDN) l ActiveWindow 返回一个Window对象表示拥有焦点的窗口
// C# public void CreateNewWindowAndTile() { // Create a new window from the active document. Word.Window wnd = ThisApplication.ActiveWindow.NewWindow(); // Tile the two windows. Object value = Word.WdArrangeStyle.wdTiled; ThisApplication.Windows.Arrange(ref value); }
tips: The Arrange method, like many methods in Word,requires C# developers to pass one or more parameters using the "ref"keyword. This means that the parameter you pass must be stored in a variablebefore you can pass it to the method. In every case, you'll need to create an Object variable, assign the variable thevalue you'd like to pass to the method, and pass the variable using the ref keyword. You'll find many examples of this technique throughout this document. --------------------------------------------------------------------------------------------------- l ActiveDocument 当前活动文档对象
l ActivePrinter 当前活动打印机
l ActiveWindow 当前活动窗口
l Caption 文档标题
// C#设置word文档标题 public void SetApplicationCaption() { // Change caption in title bar. ThisApplication.Caption = "My New Caption"; } l CapsLock 返回大小写锁定键状态
// C# public void CapsLockOn() { MessageBox.Show(ThisApplication.CapsLock.ToString()); }
l DisplayAlerts 用于设置在代码允许时如何处理警告,它有三种选项: 1.wdAlertsAll 显示所有消息和警告(默认) 2.wdAlertsMessageBox 仅显示消息框 3.wdAlertsNone 忽略任何警告 下面是该属性的常见用法:
// C# public void DisplayAlerts() { // Turn off display of messages and alerts. try { ThisApplication.DisplayAlerts = Word.WdAlertLevel.wdAlertsNone; // Your code runs here without any alerts. // . . .code doing something here. } catch (Exception ex) { // Do something with your exception. } finally { // Turn alerts on again when done. ThisApplication.DisplayAlerts = Word.WdAlertLevel.wdAlertsAll; } }
l DisplayStatusBar 可以读/写;用于表示是否显示状态栏
// C# public void ToggleStatusBar() { // Toggle display of the status bar. bool bln = ThisApplication.DisplayStatusBar; ThisApplication.DisplayStatusBar = !bln; }
l Path 返回当前应用程序的路径
// C# MessageBox.Show(ThisApplication.Path);
l Selection 只读对象,表示当前选择的区域(也可以表示光标点位置)
l UserName 读或写用户名
// C# public void ChangeUserName() { string str = ThisApplication.UserName; MessageBox.Show(str); // Change UserName. ThisApplication.UserName = "Dudley"; MessageBox.Show(ThisApplication.UserName); // Restore original UserName. ThisApplication.UserName = str; } l Visible 只有为true时才可见
// C# try { ThisApplication.Visible = false; // Do whatever it is, invisibly. } catch (Exception ex) { // Your exception handler here. } finally { ThisApplication.Visible = true; }
1.2 Application对象的方法
l CheckSpelling 检查拼写
l Help 弹出帮助对话框,有三种:WdHelp,WdHelpAbout,WdHelpSearch
// C# public void DisplayHelpAbout() { Object value = Word.WdHelpType.wdHelpAbout; ThisApplication.Help(ref value); }
l Move 移动窗口 l Resize 改变窗口大小
// C# public void MoveAndResizeWindow() { // None of this will work if the window is // maximized or minimized. ThisApplication.ActiveWindow.WindowState = Word.WdWindowState.wdWindowStateNormal; // Position at upper left corner. ThisApplication.Move(0, 0); // Size to 300 x 600 points. ThisApplication.Resize(300, 600); }
l Quit 退出Word,可以带参数WdSaveOptions:三个可选值分别是: 1.wdSaveChanges 2.wdPromptToSaveChanges 3.wdDoNotSaveChanges
// C# // Automatically save changes. Object saveChanges = Word.WdSaveOptions.wdSaveChanges; Object originalFormat = Type.Missing; Object routeDocument = Type.Missing; ThisApplication.Quit( ref saveChanges, ref originalFormat, ref routeDocument); // Prompt to save changes. saveChanges = Word.WdSaveOptions.wdPromptToSaveChanges; originalFormat = Type.Missing; routeDocument = Type.Missing; ThisApplication.Quit( ref saveChanges, ref originalFormat, ref routeDocument); // Quit without saving changes. saveChanges = Word.WdSaveOptions.wdDoNotSaveChanges; originalFormat = Type.Missing; routeDocument = Type.Missing; ThisApplication.Quit( ref saveChanges, ref originalFormat, ref routeDocument);
2. The Document Object 使用Document对象允许你对一个文档进行操作,同时由于Documents Collection的存在,你可以操作所有已经打开的文档。 参考更多:MSDN-Word2007-Document Object 2.1 Document Object Collections 一个文档可以包含一下几类对象:
2.2 引用文档 你可以引用一个Documents Collection中的Document对象。引用的方法是使用索引(1-based),例如,如下代码引用了collection中的第一个文档
// C# Word.Document doc = (Word.Document) ThisApplication.Documents[1]; 当然,你也可以通过文档的名字来引用它
// C# Word.Document doc = (Word.Document) ThisApplication.Documents["MyDoc.doc"];
2.3 打开,关闭与新建文档
l Add 新建word文档
// C# // Create a new document based on Normal.dot. Object template = Type.Missing; Object newTemplate = Type.Missing; Object documentType = Type.Missing; Object visible = Type.Missing; ThisApplication.Documents.Add( ref template, ref newTemplate, ref documentType, ref visible);
l Open 打开word文档
// C# Object filename = @"C:\Test\MyNewDocument"; Object confirmConversions = Type.Missing; Object readOnly = Type.Missing; Object addToRecentFiles = Type.Missing; Object passwordDocument = Type.Missing; Object passwordTemplate = Type.Missing; Object revert = Type.Missing; Object writePasswordDocument = Type.Missing; Object writePasswordTemplate = Type.Missing; Object format = Type.Missing; Object encoding = Type.Missing; Object visible = Type.Missing; Object openConflictDocument = Type.Missing; Object openAndRepair = Type.Missing; Object documentDirection = Type.Missing; Object noEncodingDialog = Type.Missing; ThisApplication.Documents.Open(ref filename, ref confirmConversions, ref readOnly, ref addToRecentFiles, ref passwordDocument, ref passwordTemplate, ref revert, ref writePasswordDocument, ref writePasswordTemplate, ref format, ref encoding, ref visible, ref openConflictDocument, ref openAndRepair , ref documentDirection, ref noEncodingDialog);
l Save 保存word文档
// 保存所有文档 Object noPrompt = true; Object originalFormat = Type.Missing; ThisApplication.Documents.Save(ref noPrompt, ref originalFormat); // C#保存当前文档 ThisApplication.ActiveDocument.Save();
// 保存指定名称的文档 Object file = "MyNewDocument.doc"; ThisApplication.Documents.get_Item(ref file).Save();
l SaveAs 另存为
// C# // Save the document. In a real application, // you'd want to test to see if the file // already exists. This will overwrite any previously // existing documents. Object fileName = @"C:\Test\MyNewDocument.doc"; Object fileFormat = Type.Missing; Object lockComments = Type.Missing; Object password = Type.Missing; Object addToRecentFiles = Type.Missing; Object writePassword = Type.Missing; Object readOnlyRecommended = Type.Missing; Object embedTrueTypeFonts = Type.Missing; Object saveNativePictureFormat = Type.Missing; Object saveFormsData = Type.Missing; Object saveAsAOCELetter = Type.Missing; Object encoding = Type.Missing; Object insertLineBreaks = Type.Missing; Object allowSubstitutions = Type.Missing; Object lineEnding = Type.Missing; Object addBiDiMarks = Type.Missing; ThisDocument.SaveAs(ref fileName, ref fileFormat, ref lockComments, ref password, ref addToRecentFiles, ref writePassword, ref readOnlyRecommended, ref embedTrueTypeFonts, ref saveNativePictureFormat, ref saveFormsData, ref saveAsAOCELetter, ref encoding, ref insertLineBreaks, ref allowSubstitutions, ref lineEnding, ref addBiDiMarks);
l Close 关闭word文档
// 关闭所有文档 Object saveChanges = Word.WdSaveOptions.wdSaveChanges; Object originalFormat = Type.Missing; Object routeDocument = Type.Missing; ThisApplication.Documents.Close(ref saveChanges, ref originalFormat, ref routeDocument);
// 关闭 active document Object saveChanges = Word.WdSaveOptions.wdDoNotSaveChanges; Object originalFormat = Type.Missing; Object routeDocument = Type.Missing; ThisDocument.Close( ref saveChanges, ref originalFormat, ref routeDocument); // Close MyNewDocument and save changes without prompting. Object name = "MyNewDocument.doc"; saveChanges = Word.WdSaveOptions.wdSaveChanges; originalFormat = Type.Missing; routeDocument = Type.Missing; Word.Document doc = ThisApplication.Documents.get_Item(ref name); ThisDocument.Close( ref saveChanges, ref originalFormat, ref routeDocument);
l 实例:遍历DocumentsCollection
// C# public void SaveUnsavedDocuments() { // Iterate through the Documents collection. string str; StringWriter sw = new StringWriter(); foreach (Word.Document doc in ThisApplication.Documents) { if (!doc.Saved ) { // Save the document. doc.Save(); sw.WriteLine(doc.Name); } } str = sw.ToString(); if ( str == string.Empty ) { str = "No documents need saving."; } MessageBox.Show(str, "SaveUnsavedDocuments"); } 3. The Selection Object
Selection对象代表当前选择的area。在word应用程序中,假如你要让一段字符变成黑体,你必须首先选择该段文字,然后应用样式。在代码中也是同样的道理,你要首先定义selection的区域然后进行操作。你可以使用Selection对象在文档中进行选择,格式化,操作,添加文本等。 Selection对象是始终存在的,如果当前没有选择任何东西,那么它代表一个insertion point。因此,在操作Seleciton之前知道它包含的内容是非常重要的。 Tips: Selection对象与Range对象有很多成员是类似的,它们之间的区别是Selection对象指的是现实在图形界面的区域,而Range对象代表的区域是不可见的(当然通过调用方法可以使其可见)
1.1 Using the Type Property Selection的类型有很多。比如,你要对一张表格的一列进行操作,你应该确保该列已经selected,否则会出现运行时错误。 可以通过Selection对象的 Type属性获取你需要的信息,Type属性包含一个WdSelectionType的枚举类型成员。它有如下几个值:
下面是Type属性的应用例子
// C# public void ShowSelectionType() { string str; switch (ThisApplication.Selection.Type) { case Word.WdSelectionType.wdSelectionBlock: str = "block"; break; case Word.WdSelectionType.wdSelectionColumn: str = "column"; break; case Word.WdSelectionType.wdSelectionFrame: str = "frame"; break; case Word.WdSelectionType.wdSelectionInlineShape: str = "inline shape"; break; case Word.WdSelectionType.wdSelectionIP: str = "insertion point"; break; case Word.WdSelectionType.wdSelectionNormal: str = "normal text"; break; case Word.WdSelectionType.wdNoSelection: str = "no selection"; break; case Word.WdSelectionType.wdSelectionRow: str = "row"; break; default: str = "(unknown)"; break; } MessageBox.Show(str, "ShowSelectionType"); }
1.2 Navigating and Selecting Text 为了判断什么被选中了,你也可以采用下面的方法。
1.2.1 Home and End Key Method 在使用Word时,我们知道,按下键盘的HOME键将使光标移动到光标所在行的行首,按下END键将使光标移动到行尾。在代码中,可以使用模拟按键的方法将改变selection。请看下面两个函数: HomeKey( [Unit] , [Extend] ) : 模拟按下HOME键 EndKey( [Unit] , [Extend] ) :模拟按下END键 上面的两个函数中,参数Unit有一下可选值(wdUnit类型): l Wdline 移动到一行的开始或结束位置(缺省值) l WdStory 移动到文档的开始或结束位置 l WdColumn 移动到一列的开始或结束位置(仅针对表格) l WdRow 移动到一行的开始或结束位置(仅正对表格) 参数Extend的可选值(WdMovementType类型): l WdMove 移动selection l WdExtend 扩展selection。举例说明:考虑一个场景,当前选择了一行,然后调用HomeKey方法,传入参数wdStory以及wdExtend,那么该行将不被包含在新selection对象中,同样的情况如果调用EndKey方法,那么该行将会包含在新selection对象中。
下面的示例代码演示了:移动insertion point到文档开始出,然后使用EndKey方法选中整个文档:
// C# // Position the insertion point at the beginning // of the document. Object unit = Word.WdUnits.wdStory; Object extend = Word.WdMovementType.wdMove; ThisApplication.Selection.HomeKey(ref unit, ref extend); // Select from the insertion point to the end of the document. unit = Word.WdUnits.wdStory; extend = Word.WdMovementType.wdExtend; ThisApplication.Selection.EndKey(ref unit, ref extend);
1.2.2 Arrow Key Method 既然可以模拟HOME,END键,那么当然也可以模拟按下方向键。Word提供如下四个方法,其中Count参数代表移动多少个Unit。
其中,Extend参数使用的是与END,HOME相同的枚举类型变量,它包含两个可选值:wdMove,wdExtend. 而移动单元(Unit)类型与前面的有所不同,而且针对左右 |
请发表评论