Word对象模型 (.Net Perspective)
本文主要针对在Visual Studio中使用C# 开发关于Word的应用程序
来源:Understandingthe Word Object Model from a .NET Developer's Perspective
五大对象
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对象也代表文档中的一块区域,它具有以下特点
- 包含一个起始位置和一个结束位置
- 它可以包含光标点,一段文本或者整个文档
- 它包含空格,tab以及paragraph marks
- 它可以是当前选中的区域,当然也可以不是当前选中区域
- 它被动态创建
- 当你在一个Range的末尾插入文本,这将扩展该Range
l Bookmark对象也代表一块区域,一般使用Bookmark来标记文档中的位置,它有如下特点
- 书签一般有名字
- Saved with the document,且文档关闭了之后书签继续存在
- 书签通常是隐藏的,但也可以通过代码设置其为可见
---------------------------------------------------------------------------------------------
下面分别介绍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);
- }
// 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";
- }
// 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());
- }
// 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;
- }
- }
// 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;
- }
// C# public void ToggleStatusBar() { // Toggle display of the status bar. bool bln = ThisApplication.DisplayStatusBar; ThisApplication.DisplayStatusBar = !bln; }
l Path 返回当前应用程序的路径
- // C#
- MessageBox.Show(ThisApplication.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;
- }
// 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;
- }
// 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);
- }
// 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);
- }
// 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);
// 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
一个文档可以包含一下几类对象:
- l Characters
- l Words
- l Sentences
- l Paragraphs
- l Sections
- l Headers/Footers
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[1];
当然,你也可以通过文档的名字来引用它
- // C#
- Word.Document doc =
- (Word.Document) ThisApplication.Documents["MyDoc.doc"];
// 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);
// 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:TestMyNewDocument";
- 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);
// C# Object filename = @"C:TestMyNewDocument"; 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 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();
// 保存指定名称的文档 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:TestMyNewDocument.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);
// 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:TestMyNewDocument.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);
// 关闭所有文档 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);
// 关闭 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");
- }
// 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的枚举类型成员。它有如下几个值:
- wdSelectionBlock
- wdSelectionColumn
- wdSelectionFrame
- wdSelectionInlineShape 表示一幅图片
- wdSelectionIP 表示插入点(insertion point)
- wdSelectionNormal 表示选中的文本或者文本和其他对象的组合
- wdNoSelection
- wdSelectionRow
- wdSelectionShape
下面是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");
- }
// 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);
// 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。
- MoveLeft([Unit], [Count], [Extend])
- MoveRight([Unit], [Count], [Extend])
- MoveUp([Unit], [Count], [Extend])
- MoveDown([Unit], [Count], [Extend])
其中,Extend参数使用的是与END,HOME相同的枚举类型变量,它包含两个可选值:wdMove,wdExtend.
而移动单元(Unit)类型与前面的有所不同,而且针对左右移动和上下移动有所区分。
- 左右移动时对应的单元类型 MoveLeft() MoveRight()
- wdCharacter: 字符(缺省)
- wdWord: 单词
- wdCell: 单元格(仅对表格)
- wdSentence: 句子
下面的代码演示了:向左移动插入点三个字符,然后选择插入点右边的三个单词
- // C#
- // Move the insertion point left 3 characters.
- Object unit = Word.WdUnits.wdCharacter;
- Object count = 3;
- Object extend = Word.WdMovementType.wdMove;
- ThisApplication.Selection.MoveLeft(ref unit, ref count,
- ref extend);
- // Select the 3 words to the right of the insertion point.
- unit = Word.WdUnits.wdWord;
- count = 3;
- extend = Word.WdMovementType.wdExtend;
- ThisApplication.Selection.MoveRight(ref unit, ref count,
- ref extend);
// C# // Move the insertion point left 3 characters. Object unit = Word.WdUnits.wdCharacter; Object count = 3; Object extend = Word.WdMovementType.wdMove; ThisApplication.Selection.MoveLeft(ref unit, ref count, ref extend); // Select the 3 words to the right of the insertion point. unit = Word.WdUnits.wdWord; count = 3; extend = Word.WdMovementType.wdExtend; ThisApplication.Selection.MoveRight(ref unit, ref count, ref extend);
- 上下移动时对应的单元类型 MoveUp() MoveDown()
- wdLine :行 (缺省)
- wdParagraph :段落
- wdWindow :窗口
- wdScreen :屏幕大小
下面的例子演示了使用上述方法先把插入点向上移动一行,然后选择其后的三个段落。
- // C#
- // Move the insertion point up one line.
- Object unit = Word.WdUnits.wdLine;
- Object count = 1;
- Object extend = Word.WdMovementType.wdMove;
- ThisApplication.Selection.MoveUp(ref unit, ref count, ref extend);
- // Select the following 3 paragraphs.
- unit = Word.WdUnits.wdParagraph;
- count = 3;
- extend = Word.WdMovementType.wdMove;
- ThisApplication.Selection.MoveDown(ref unit, ref count,
- ref extend);
// C# // Move the insertion point up one line. Object unit = Word.WdUnits.wdLine; Object count = 1; Object extend = Word.WdMovementType.wdMove; ThisApplication.Selection.MoveUp(ref unit, ref count, ref extend); // Select the following 3 paragraphs. unit = Word.WdUnits.wdParagraph; count = 3; extend = Word.WdMovementType.wdMove; ThisApplication.Selection.MoveDown(ref unit, ref count, ref extend);
3.2.3 Move Method
使用Move方法将改变指定的range或者selection。
下面的例子将使插入点移动到第三个单词之前
- // Use the Move method to move 3 words.
- Obiect unit = Word.WdUnits.wdWord;
- Object count = 3;
- ThisApplication.Selection.Move(ref unit, ref count);
// Use the Move method to move 3 words. Obiect unit = Word.WdUnits.wdWord; Object count = 3; ThisApplication.Selection.Move(ref unit, ref count);
3.2.4 Inserting Text
最简单的在文档中插入文本的方法是使用Selection对象的TypeText方法。TypeText方法的行为由用户的选择决定。下面这个例子就使用了一个叫做 overtype 的选项。该选项如果被打开,那么插入字符将导致插入点后面的文本被覆盖。
----------------------------------------------------------------------------
重要的例子 演示如何插入文本
(若selection类型不是insertion point或者 a block of text ,那么下面的代码do nothing)
- public void InsertTextAtSelection()
- {
- Word.Selection sln = ThisApplication.Selection;
- // Make sure overtype is turned off.
- ThisApplication.Options.Overtype = false;
- //当前的selection对象是否为插入点
- //如果是,那么插入一段字符,然后插入段标记
- if (sln.Type == Word.WdSelectionType.wdSelectionIP )
- {
- sln.TypeText("Inserting at insertion point. ");
- sln.TypeParagraph();//插入paragraph mark
- }
- //selection对象是否为normal 类型
- else if (sln.Type == Word.WdSelectionType.wdSelectionNormal )
- {
- // 查看ReplaceSelection选项是否开启
- //如果开启,那么摧毁该selection,同时将selection对象修改为插入点类型//且定位到之前的selection区域头部
- if ( ThisApplication.Options.ReplaceSelection )
- {
- Object direction = Word.WdCollapseDirection.wdCollapseStart;
- sln.Collapse(ref direction);
- }
- //插入文本与段落标记
- sln.TypeText("Inserting before a text block. ");
- sln.TypeParagraph();
- }
- else
- {
- // Do nothing.
- }
- }
- -----------------------------------------------------------------------
public void InsertTextAtSelection() { Word.Selection sln = ThisApplication.Selection; // Make sure overtype is turned off. ThisApplication.Options.Overtype = false; //当前的selection对象是否为插入点 //如果是,那么插入一段字符,然后插入段标记 if (sln.Type == Word.WdSelectionType.wdSelectionIP ) { sln.TypeText("Inserting at insertion point. "); sln.TypeParagraph();//插入paragraph mark } //selection对象是否为normal 类型 else if (sln.Type == Word.WdSelectionType.wdSelectionNormal ) { // 查看ReplaceSelection选项是否开启 //如果开启,那么摧毁该selection,同时将selection对象修改为插入点类型//且定位到之前的selection区域头部 if ( ThisApplication.Options.ReplaceSelection ) { Object direction = Word.WdCollapseDirection.wdCollapseStart; sln.Collapse(ref direction); } //插入文本与段落标记 sln.TypeText("Inserting before a text block. "); sln.TypeParagraph(); } else { // Do nothing. } } -----------------------------------------------------------------------
4. The Range Object
Range对象也代表一个区域。与使用Selection相比较,Range的优势在于
l 执行给定任务需要较少的代码
l 不需要改变当前文档的选中区域(donot have to change the highlighting)
l Has greater capabilities
4.1 定义并选择一个Range
下面的代码新建一个Range对象,并选择文档的前7个字符,包括non-printing字符,然后使用Select方法是Range可见(即高亮显示)。如果不使用Select方法,在Word界面中你将看不到Range对象的区域,但是可以在程序中操作。
- // C#
- Object start = 0;
- Object end = 7;
- Word.Range rng = ThisDocument.Range(ref start, ref end);
- rng.Select();
// C# Object start = 0; Object end = 7; Word.Range rng = ThisDocument.Range(ref start, ref end); rng.Select();
1.1.1 Counting Characters
- // 选择整个文档,并显示字符总数
- Object start = Type.Missing;
- Object end = ThisDocument.Characters.Count;
- Word.Range rng = ThisDocument.Range(ref start, ref end);
- rng.Select();
- MessageBox.Show("Characters: " +
- ThisDocument.Characters.Count.ToString());
// 选择整个文档,并显示字符总数 Object start = Type.Missing; Object end = ThisDocument.Characters.Count; Word.Range rng = ThisDocument.Range(ref start, ref end); rng.Select(); MessageBox.Show("Characters: " + ThisDocument.Characters.Count.ToString());
1.1.2 Setting Up Ranges
你可以使用Content属性使Range包含整个文档内容
- // C#
- Word.Range rng = ThisDocument.Content;
// C# Word.Range rng = ThisDocument.Content;
下面的例子完成以下功能:
- 新建一个 Range变量
- 检查文档中是否至少含有两个句子
- 使Range的起始点为第二个句子的开头
- 使Range的结束点为第二个句子的结尾
- 高亮显示该Range
- public void SelectSentence()
- {
- Word.Range rng;
- if (ThisDocument.Sentences.Count >= 2 )
- {
- // Supply a Start and end value for the Range.
- Object start = ThisDocument.Sentences[2].Start;
- Object end = ThisDocument.Sentences[2].End;
- rng = ThisDocument.Range(ref start, ref end);
- rng.Select();
- }
- }
public void SelectSentence() { Word.Range rng; if (ThisDocument.Sentences.Count >= 2 ) { // Supply a Start and end value for the Range. Object start = ThisDocument.Sentences[2].Start; Object end = ThisDocument.Sentences[2].End; rng = ThisDocument.Range(ref start, ref end); rng.Select(); } }
4.2 扩展Range
定义Range对象后,可以使用MoveStart和MoveEnd方法扩展它的范围。这两个函数使用两个相同的参数:Unit与Count。其中Unit参数是WdUnits类型,它有如下可选值:
- wdCharacter
- wdWord
- wdSentence
- wdParagraph
- wdSection
- wdStory
- wdCell
- wdColumn
- wdRow
- wdTable
下面的例子演示了:定义一个Range包含文档的前7个字符,然后移动其开始点7个字符长度,于是结果是原来的Range变成了一个insertion point;然后使用MoveEnd方法使其结束点移动7个字符
- // C#
- // Define a range of 7 characters.
- Object start = 0;
- Object end = 7;
- Word.Range rng = ThisDocument.Range(ref start, ref end);
- // Move the starting position 7 characters.
- Object unit = Word.WdUnits.wdCharacter;
- Object count = 7;
- rng.MoveStart(ref unit, ref count);
- // Move the ending position 7 characters.
- unit = Word.WdUnits.wdCharacter;
- count = 7;
- rng.MoveEnd(ref unit, ref count);
// C# // Define a range of 7 characters. Object start = 0; Object end = 7; Word.Range rng = ThisDocument.Range(ref start, ref end); // Move the starting position 7 characters. Object unit = Word.WdUnits.wdCharacter; Object count = 7; rng.MoveStart(ref unit, ref count); // Move the ending position 7 characters. unit = Word.WdUnits.wdCharacter; count = 7; rng.MoveEnd(ref unit, ref count);
下图展示了上述代码的移动过程
4.3 获得Range的首字符和尾字符
- MessageBox.Show(String.Format("Start: {0}, End: {1}",
- rng.Start, rng.End), "Range Start and End");
MessageBox.Show(String.Format("Start: {0}, End: {1}", rng.Start, rng.End), "Range Start and End");
4.4 使用SetRange方法
- // C#
- Word.Range rng;
- Object start = 0;
- Object end = 7;
- rng = ThisDocument.Range(ref start, ref end);
- // Reset the existing Range.
- rng.SetRange(ThisDocument.Sentences[2].Start,
- ThisDocument.Sentences[5].End);
- rng.Select();
// C# Word.Range rng; Object start = 0; Object end = 7; rng = ThisDocument.Range(ref start, ref end); // Reset the existing Range. rng.SetRange(ThisDocument.Sentences[2].Start, ThisDocument.Sentences[5].End); rng.Select();
4.5 格式化文本
若要给Range指定格式,你首先需要指定一个Range,然后应用格式。
下面的代码演示了如下过程:
1. 选择文档中的第一段,然后设置字号字体以及对齐,
2. 弹出对话框
3. 调用三次Undo方法回退之前的操作
4. 应用Normal IndentStyle然后弹出对话框
5. 调用一次Undo方法然后弹出对话框
- // C#
- public void FormatRangeAndUndo()
- {
- // Set the Range to the first paragraph.
- Word.Range rng = ThisDocument.Paragraphs[1].Range;
- // Change the formatting.
- rng.Font.Size = 14;
- rng.Font.Name = "Arial";
- rng.ParagraphFormat.Alignment =
- Word.WdParagraphAlignment.wdAlignParagraphCenter;
- rng.Select();
- MessageBox.Show("Formatted Range", "FormatRangeAndUndo");
- // Undo the three previous actions.
- Object times = 3;
- ThisDocument.Undo(ref times);
- rng.Select();
- MessageBox.Show("Undo 3 actions", "FormatRangeAndUndo");
- // Apply the Normal Indent style.
- Object style = "Normal Indent";
- rng.set_Style(ref style);
- rng.Select();
- MessageBox.Show("Normal Indent style applied",
- "FormatRangeAndUndo");
- // Undo a single action.
- times = 1;
- ThisDocument.Undo(ref times);
- rng.Select();
- MessageBox.Show("Undo 1 action", "FormatRangeAndUndo");
- }
// C# public void FormatRangeAndUndo() { // Set the Range to the first paragraph. Word.Range rng = ThisDocument.Paragraphs[1].Range; // Change the formatting. rng.Font.Size = 14; rng.Font.Name = "Arial"; rng.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter; rng.Select(); MessageBox.Show("Formatted Range", "FormatRangeAndUndo"); // Undo the three previous actions. Object times = 3; ThisDocument.Undo(ref times); rng.Select(); MessageBox.Show("Undo 3 actions", "FormatRangeAndUndo"); // Apply the Normal Indent style. Object style = "Normal Indent"; rng.set_Style(ref style); rng.Select(); MessageBox.Show("Normal Indent style applied", "FormatRangeAndUndo"); // Undo a single action. times = 1; ThisDocument.Undo(ref times); rng.Select(); MessageBox.Show("Undo 1 action", "FormatRangeAndUndo"); }
4.6 插入文本
你可以使用Range对象的Text属性用于向文档中插入文本。下面的代码在文档的开始处插入 “New Text”字符串。然后选择该区域。
- // C#
- string str = " new Text ";
- Object start = 0;
- Object end = 0;
- Word.Range rng = ThisDocument.Range(ref start, ref end);
- rng.Text = str;
- rng.Select();
// C# string str = " new Text "; Object start = 0; Object end = 0; Word.Range rng = ThisDocument.Range(ref start, ref end); rng.Text = str; rng.Select();
4.7 替换文本
- // C#
- start = 0;
- end = 12;
- rng = ThisDocument.Range(ref start, ref end);
- rng.Text = str;
- rng.Select();
// C# start = 0; end = 12; rng = ThisDocument.Range(ref start, ref end); rng.Text = str; rng.Select();
4.8 Collapsing a Range of Selection
当使用Range对象或者Selection对象时,有可能需要在一段文字前插入文本的同时又不想覆盖原来的文本,Range对象和Selection对象都有Collapse方法,该方法使用了两个枚举值:
WdCollapseStart:Collapses the selection to thebeginning of itself
WdCollapseEnd:Collapsesthe selection to the end of itself
下面的例子首先创建一个Range,然后使其包含文档的第一段,然后使用wdCollapseStart枚举值Collapse该Range,然后插入新文本。
- // C#
- string str = " new Text ";
- Word.Range rng = ThisDocument.Paragraphs[1].Range;
- Object direction = Word.WdCollapseDirection.wdCollapseStart;
- rng.Collapse(ref direction);
- rng.Text = str;
- rng.Select();
// C# string str = " new Text "; Word.Range rng = ThisDocument.Paragraphs[1].Range; Object direction = Word.WdCollapseDirection.wdCollapseStart; rng.Collapse(ref direction); rng.Text = str; rng.Select();
若使用wdCollapseEnd,即:
- // C#
- Object direction = Word.WdCollapseDirection.wdCollapseEnd;
- rng.Collapse(ref direction);
// C# Object direction = Word.WdCollapseDirection.wdCollapseEnd; rng.Collapse(ref direction);
结果如下:
Tips : Collapse不是很好去翻译,通俗的说,它的功能是:当你的Range对象或者Selection对象包含的内容是一段文字时,使用Collapse()方法可以使 Range或者Selection包含的区域变成原来那段文字的前插入点或者后插入点
4.9 Paragraph Mark 段落标记
下面的代码把文档中的前两段相互交换位置
重要例子
- public void ManipulateRangeText()
- {
- // Retrieve contents of first and second paragraphs
- string str1 = ThisDocument.Paragraphs[1].Range.Text;
- string str2 = ThisDocument.Paragraphs[2].Range.Text;
- // 两个自然段相互交换
- Word.Range rng1 = ThisDocument.Paragraphs[1].Range;
- rng1.Text = str2;
- Word.Range rng2 = ThisDocument.Paragraphs[2].Range;
- rng2.Text = str1;
- // 显示结果
- rng1.Select();
- MessageBox.Show(rng1.Text, "ManipulateRangeText");
- rng2.Select();
- MessageBox.Show(rng2.Text, "ManipulateRangeText");
- Object unit = Word.WdUnits.wdCharacter;
- Object count = -1;
- rng1.MoveEnd(ref unit, ref count);
- // Write new text for paragraph 1.
- rng1.Text = "new content for paragraph 1.";
- rng2.Text = "new content for paragraph 2.";
- // Pause to display the results.
- rng1.Select();
- MessageBox.Show(rng1.Text, "ManipulateRangeText");
- rng2.Select();
- MessageBox.Show(rng2.Text, "ManipulateRangeText");
- unit = Word.WdUnits.wdCharacter;
- count = 1;
- rng1.MoveEnd(ref unit, ref count);
- // Note that in C#, you must specify
- // both parameters--it's up to you
- // to calculate the length of the range.
- unit = Word.WdUnits.wdCharacter;
- count = rng2.Characters.Count;
- rng2.Delete(ref unit, ref count);
- // C#
- rng1.Text = str1;
- // C#
- rng1.InsertAfter(str2);
- rng1.Select();
- }