VSTO开发记录
01-VSTO开发控件篇
Visual Studio 需要对此项目进行非功能性更改是什么意思?
VSTO开发 FolderBrowserDialog文件夹选择控件的使用
VSTO开发 FontDialog选择字体基础使用
VB读写配置文件(ini)
用 VB.NET 编写简单淋漓软件版本更新源码 | 淋漓网络官方博客
02-VSTO开发word篇
WORD VBA 实现光标移动与内容选择 - Word VBA - Office 交流网
VSTO(C#)对 Word 开发积累_走在成长的路上 - CSDN 博客
VSTO开发 VB获取系统字体列表
C# 操作 Word (1)Word 对象模型
Word VBA 在文档最后一页右下角插入图片(盖章)
C#和VB开发更新功能
03-VSTO开发EXCEL篇
处理 Selection 对象和 Range 对象——Word VBA 中重要的两个对象_foreverfall 的博客 - CSDN 博客_excel selection 撖寡情
04-VSTO开发PPT篇
05-VSTO开发工具篇
本文档使用 MrDoc 发布
-
+
home page
C# 操作 Word (1)Word 对象模型
> 本文由 [简悦 SimpRead](http://ksria.com/simpread/) 转码, 原文地址 [blog.csdn.net](https://blog.csdn.net/ruby97/article/details/7406806) **Word 对象模型 (.Net Perspective)** 本文主要针对在 Visual Studio 中使用 **C#** 开发关于 **Word** 的应用程序 来源:[Understandingthe Word Object Model from a .NET Developer's Perspective](http://msdn.microsoft.com/en-us/library/aa192495%28v=office.11%29.aspx) =================================================================================================================================================== 五大对象 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](http://msdn.microsoft.com/en-us/library/bb244569%28v=office.12%29.aspx) **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](http://msdn.microsoft.com/en-us/library/bb244898%28v=office.12%29.aspx) **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["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 的枚举类型成员。它有如下几个值: * 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"); } ``` **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。 * **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); ``` * **上下移动时对应的单元类型 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); ``` **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); ``` **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. } } ----------------------------------------------------------------------- ``` 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(); ``` **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()); ``` **1.1.2 Setting Up Ranges** 你可以使用 Content 属性使 Range 包含整个文档内容 ``` // 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(); } } ``` **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); ``` 下图展示了上述代码的移动过程 **4.3 获得 Range 的首字符和尾字符** ``` 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(); ``` **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"); } ``` **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(); ``` **4.7 替换文本** ``` // 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(); ``` 若使用 wdCollapseEnd,即: ``` // 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(); } ``` 本文概要性的介绍了 word2007 的几大对象,主要是一些 API 的应用。后面将会通过实例,结合 VS2010;来实现 C# 对 Word 的操作。 本文的 PDF 版本下载: [C# 操作 Word2007_v1.0.pdf](http://download.csdn.net/detail/ruby97/4183223) 另有 C# 操作 Excel 的 PDF 下载:[C# 操作 Excel2007_v1.0.pdf](http://download.csdn.net/detail/ruby97/4177580)
似最初
Feb. 8, 2022, 10:32 a.m.
转发文档
Collection documents
Last
Next
手机扫码
Copy link
手机扫一扫转发分享
Copy link
关于 MrDoc
觅思文档MrDoc
是
州的先生
开发并开源的在线文档系统,其适合作为个人和小型团队的云笔记、文档和知识库管理工具。
如果觅思文档给你或你的团队带来了帮助,欢迎对作者进行一些打赏捐助,这将有力支持作者持续投入精力更新和维护觅思文档,感谢你的捐助!
>>>捐助鸣谢列表
微信
支付宝
QQ
PayPal
Markdown文件
share
link
type
password
Update password