星空网 > 软件开发 > ASP.net

c#中操作word文档

转自:http://blog.csdn.net/ruby97/article/details/7406806

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的对象结构图:

c#中操作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对象表示拥有焦点的窗口

 

[csharp] view plaincopy 


  1. // C#  
  2. public void CreateNewWindowAndTile()  
  3. {  
  4.    // Create a new window from the active document.  
  5.    Word.Window wnd = ThisApplication.ActiveWindow.NewWindow();  
  6.    
  7.    // Tile the two windows.  
  8.    Object value = Word.WdArrangeStyle.wdTiled;  
  9.    ThisApplication.Windows.Arrange(ref value);  
  10. }  



 

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                     文档标题

[csharp] view plaincopy 


  1. // C#设置word文档标题  
  2. public void SetApplicationCaption()   
  3. {  
  4.     // Change caption in title bar.  
  5.     ThisApplication.Caption = "My New Caption";  
  6. }  




l  CapsLock   返回大小写锁定键状态

[csharp] view plaincopy 


  1. // C#  
  2. public void CapsLockOn()   
  3. {  
  4.     MessageBox.Show(ThisApplication.CapsLock.ToString());  
  5. }  




 

l  DisplayAlerts 用于设置在代码允许时如何处理警告,它有三种选项:       

1.wdAlertsAll                                显示所有消息和警告(默认)

2.wdAlertsMessageBox                 仅显示消息框

3.wdAlertsNone                             忽略任何警告

下面是该属性的常见用法:

[csharp] view plaincopy 


  1. // C#  
  2. public void DisplayAlerts()   
  3. {  
  4.     // Turn off display of messages and alerts.  
  5.     try   
  6.     {  
  7.         ThisApplication.DisplayAlerts = Word.WdAlertLevel.wdAlertsNone;  
  8.         // Your code runs here without any alerts.  
  9.         // . . .code doing something here.  
  10.    
  11.     }   
  12.     catch (Exception ex)  
  13.     {  
  14.         // Do something with your exception.  
  15.    
  16.     }   
  17.     finally   
  18.     {  
  19.         // Turn alerts on again when done.  
  20.         ThisApplication.DisplayAlerts = Word.WdAlertLevel.wdAlertsAll;  
  21.     }  
  22. }  




 

 

l  DisplayStatusBar      可以读/写;用于表示是否显示状态栏

[csharp] view plaincopy 


  1. // C#  
  2. public void ToggleStatusBar()   
  3. {  
  4.     // Toggle display of the status bar.  
  5.     bool bln = ThisApplication.DisplayStatusBar;  
  6.     ThisApplication.DisplayStatusBar = !bln;  
  7. }  




 

l  Path           返回当前应用程序的路径

[csharp] view plaincopy 


  1. // C#  
  2. MessageBox.Show(ThisApplication.Path);  




 

l  Selection    只读对象,表示当前选择的区域(也可以表示光标点位置)

 

l  UserName  读或写用户名

[csharp] view plaincopy 


  1. // C#  
  2. public void ChangeUserName()   
  3. {  
  4.     string  str = ThisApplication.UserName;  
  5.     MessageBox.Show(str);  
  6.    
  7.     // Change UserName.  
  8.     ThisApplication.UserName = "Dudley";  
  9.     MessageBox.Show(ThisApplication.UserName);  
  10.     // Restore original UserName.  
  11.     ThisApplication.UserName = str;  
  12. }  




l  Visible        只有为true时才可见

[csharp] view plaincopy 


  1. // C#  
  2. try   
  3. {  
  4.     ThisApplication.Visible = false;  
  5.     // Do whatever it is, invisibly.  
  6. }   
  7. catch (Exception ex)  
  8. {  
  9.     // Your exception handler here.  
  10. }   
  11. finally   
  12. {  
  13.     ThisApplication.Visible = true;  
  14. }  




 

1.2      Application对象的方法

 

l  CheckSpelling 检查拼写

 

l  Help 弹出帮助对话框,有三种:WdHelp,WdHelpAbout,WdHelpSearch

[csharp] view plaincopy 


  1. // C#  
  2. public void DisplayHelpAbout()   
  3. {  
  4.     Object value = Word.WdHelpType.wdHelpAbout;  
  5.     ThisApplication.Help(ref value);  
  6. }  




 

l  Move         移动窗口

l  Resize        改变窗口大小

[csharp] view plaincopy 


  1. // C#  
  2. public void MoveAndResizeWindow()   
  3. {  
  4.     // None of this will work if the window is   
  5.     // maximized or minimized.  
  6.     ThisApplication.ActiveWindow.WindowState =   
  7.         Word.WdWindowState.wdWindowStateNormal;  
  8.    
  9.     // Position at upper left corner.  
  10.     ThisApplication.Move(0, 0);  
  11.    
  12.     // Size to 300 x 600 points.  
  13.     ThisApplication.Resize(300, 600);  
  14. }  




 

l  Quit           退出Word,可以带参数WdSaveOptions:三个可选值分别是:      

1.wdSaveChanges

        2.wdPromptToSaveChanges

        3.wdDoNotSaveChanges

[csharp] view plaincopy 


  1. // C#  
  2. // Automatically save changes.  
  3. Object saveChanges     = Word.WdSaveOptions.wdSaveChanges;  
  4. Object originalFormat  = Type.Missing;  
  5. Object routeDocument   = Type.Missing;  
  6. ThisApplication.Quit(  ref saveChanges,   
  7.                        ref originalFormat,   
  8.                        ref routeDocument);  
  9.    
  10. // Prompt to save changes.  
  11. saveChanges    = Word.WdSaveOptions.wdPromptToSaveChanges;  
  12. originalFormat  = Type.Missing;  
  13. routeDocument  = Type.Missing;  
  14. ThisApplication.Quit(  ref saveChanges,   
  15.                        ref originalFormat,   
  16.                        ref routeDocument);  
  17.    
  18. // Quit without saving changes.  
  19. saveChanges    = Word.WdSaveOptions.wdDoNotSaveChanges;  
  20. originalFormat  = Type.Missing;  
  21. routeDocument  = Type.Missing;  
  22. ThisApplication.Quit(  ref saveChanges,   
  23.                        ref originalFormat,   
  24.                        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中的第一个文档

[csharp] view plaincopy 


  1. // C#  
  2. Word.Document doc = (Word.Document) ThisApplication.Documents[1];  




当然,你也可以通过文档的名字来引用它

[csharp] view plaincopy 


  1. // C#  
  2. Word.Document doc =   
  3.     (Word.Document) ThisApplication.Documents["MyDoc.doc"];  




 

2.3        打开,关闭与新建文档

 

l  Add           新建word文档  

[csharp] view plaincopy 


  1. // C#  
  2. // Create a new document based on Normal.dot.  
  3. Object template = Type.Missing;  
  4. Object newTemplate = Type.Missing;  
  5. Object documentType = Type.Missing;  
  6. Object visible = Type.Missing;   
  7.    
  8. ThisApplication.Documents.Add(   
  9.   ref template, ref newTemplate, ref documentType, ref visible);  




 

l  Open 打开word文档

[csharp] view plaincopy 


  1. // C#  
  2. Object filename = @"C:\Test\MyNewDocument";  
  3. Object confirmConversions = Type.Missing;  
  4. Object readOnly = Type.Missing;  
  5. Object addToRecentFiles = Type.Missing;  
  6. Object passwordDocument = Type.Missing;  
  7. Object passwordTemplate = Type.Missing;  
  8. Object revert = Type.Missing;  
  9. Object writePasswordDocument = Type.Missing;  
  10. Object writePasswordTemplate = Type.Missing;  
  11. Object format = Type.Missing;  
  12. Object encoding = Type.Missing;  
  13. Object visible = Type.Missing;  
  14. Object openConflictDocument = Type.Missing;  
  15. Object openAndRepair  = Type.Missing;  
  16. Object documentDirection = Type.Missing;  
  17. Object noEncodingDialog = Type.Missing;  
  18.    
  19. ThisApplication.Documents.Open(ref filename,   
  20.     ref confirmConversions, ref readOnly, ref addToRecentFiles,   
  21.     ref passwordDocument, ref passwordTemplate, ref revert,   
  22.     ref writePasswordDocument, ref writePasswordTemplate,   
  23.     ref format, ref encoding, ref visible, ref openConflictDocument,   
  24.     ref openAndRepair , ref documentDirection, ref noEncodingDialog);  




 

l  Save 保存word文档

[csharp] view plaincopy 


  1. // 保存所有文档  
  2. Object noPrompt = true;  
  3. Object originalFormat = Type.Missing;  
  4. ThisApplication.Documents.Save(ref noPrompt, ref originalFormat);  
  5.    
  6. // C#保存当前文档  
  7. ThisApplication.ActiveDocument.Save();  
  8.    




 

[csharp] view plaincopy 


  1. // 保存指定名称的文档  
  2. Object file = "MyNewDocument.doc";  
  3. ThisApplication.Documents.get_Item(ref file).Save();  




 

l  SaveAs 另存为

[csharp] view plaincopy 


  1. // C#  
  2. // Save the document. In a real application,  
  3. // you'd want to test to see if the file  
  4. // already exists. This will overwrite any previously   
  5. // existing documents.  
  6. Object fileName = @"C:\Test\MyNewDocument.doc";  
  7. Object fileFormat = Type.Missing;  
  8. Object lockComments = Type.Missing;  
  9. Object password = Type.Missing;  
  10. Object addToRecentFiles = Type.Missing;  
  11. Object writePassword = Type.Missing;  
  12. Object readOnlyRecommended = Type.Missing;  
  13. Object embedTrueTypeFonts = Type.Missing;  
  14. Object saveNativePictureFormat = Type.Missing;  
  15. Object saveFormsData = Type.Missing;  
  16. Object saveAsAOCELetter = Type.Missing;  
  17. Object encoding = Type.Missing;  
  18. Object insertLineBreaks = Type.Missing;  
  19. Object allowSubstitutions = Type.Missing;  
  20. Object lineEnding = Type.Missing;  
  21. Object addBiDiMarks = Type.Missing;  
  22.    
  23. ThisDocument.SaveAs(ref fileName, ref fileFormat, ref lockComments,   
  24.   ref password, ref addToRecentFiles, ref writePassword,   
  25.   ref readOnlyRecommended, ref embedTrueTypeFonts,   
  26.   ref saveNativePictureFormat, ref saveFormsData,   
  27.   ref saveAsAOCELetter, ref encoding, ref insertLineBreaks,   
  28.   ref allowSubstitutions, ref lineEnding, ref addBiDiMarks);  




 

 

l  Close 关闭word文档

[csharp] view plaincopy 


  1. // 关闭所有文档  
  2. Object saveChanges     = Word.WdSaveOptions.wdSaveChanges;  
  3. Object originalFormat  = Type.Missing;  
  4. Object routeDocument   = Type.Missing;  
  5. ThisApplication.Documents.Close(ref saveChanges,   
  6.                                ref originalFormat,   
  7.                                ref routeDocument);  




 

[csharp] view plaincopy 


  1. // 关闭 active document   
  2. Object saveChanges     = Word.WdSaveOptions.wdDoNotSaveChanges;  
  3. Object originalFormat  = Type.Missing;  
  4. Object routeDocument   = Type.Missing;  
  5. ThisDocument.Close(    ref saveChanges,   
  6.                        ref originalFormat,  
  7.                        ref routeDocument);  
  8.    
  9. // Close MyNewDocument and save changes without prompting.  
  10. Object name     = "MyNewDocument.doc";  
  11. saveChanges    = Word.WdSaveOptions.wdSaveChanges;  
  12. originalFormat  = Type.Missing;  
  13. routeDocument  = Type.Missing;  
  14.    
  15. Word.Document doc = ThisApplication.Documents.get_Item(ref name);  
  16. ThisDocument.Close(    ref saveChanges,   
  17.                        ref originalFormat,   
  18.                        ref routeDocument);  




 

l  实例:遍历DocumentsCollection

[csharp] view plaincopy 


  1. // C#  
  2. public void SaveUnsavedDocuments()   
  3. {  
  4.     // Iterate through the Documents collection.  
  5.     string  str;  
  6.     StringWriter  sw = new StringWriter();  
  7.    
  8.     foreach (Word.Document doc in ThisApplication.Documents)  
  9.     {  
  10.         if (!doc.Saved )   
  11.         {  
  12.             // Save the document.  
  13.             doc.Save();  
  14.             sw.WriteLine(doc.Name);  
  15.         }  
  16.     }   
  17.    
  18.     str = sw.ToString();  
  19.     if ( str == string.Empty )   
  20.     {  
  21.     str = "No documents need saving.";  
  22.     }   
  23.     MessageBox.Show(str, "SaveUnsavedDocuments");  
  24. }  




 

3The 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属性的应用例子

[csharp] view plaincopy 


  1. // C#  
  2. public void ShowSelectionType()   
  3. {  
  4.     string  str;  
  5.     switch (ThisApplication.Selection.Type)   
  6.     {  
  7.         case Word.WdSelectionType.wdSelectionBlock:  
  8.             str = "block";  
  9.             break;  
  10.         case Word.WdSelectionType.wdSelectionColumn:  
  11.             str = "column";  
  12.             break;  
  13.         case Word.WdSelectionType.wdSelectionFrame:  
  14.             str = "frame";  
  15.             break;  
  16.         case Word.WdSelectionType.wdSelectionInlineShape:  
  17.             str = "inline shape";  
  18.             break;  
  19.         case Word.WdSelectionType.wdSelectionIP:  
  20.             str = "insertion point";  
  21.             break;  
  22.         case Word.WdSelectionType.wdSelectionNormal:  
  23.             str = "normal text";  
  24.             break;  
  25.         case Word.WdSelectionType.wdNoSelection:  
  26.             str = "no selection";  
  27.             break;  
  28.         case Word.WdSelectionType.wdSelectionRow:  
  29.             str = "row";  
  30.             break;  
  31.         default:  
  32.             str = "(unknown)";  
  33.             break;  
  34.     }  
  35.     MessageBox.Show(str, "ShowSelectionType");  
  36. }  




 

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方法选中整个文档:

[csharp] view plaincopy 


  1. // C#  
  2. // Position the insertion point at the beginning   
  3. // of the document.  
  4. Object unit     = Word.WdUnits.wdStory;  
  5. Object extend   = Word.WdMovementType.wdMove;  
  6. ThisApplication.Selection.HomeKey(ref unit, ref extend);  
  7.    
  8. // Select from the insertion point to the end of the document.  
  9. unit    = Word.WdUnits.wdStory;  
  10. extend  = Word.WdMovementType.wdExtend;  
  11. 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: 句子

下面的代码演示了:向左移动插入点三个字符,然后选择插入点右边的三个单词

[csharp] view plaincopy 


  1. // C#  
  2. // Move the insertion point left 3 characters.  
  3. Object unit = Word.WdUnits.wdCharacter;  
  4. Object count = 3;  
  5. Object extend = Word.WdMovementType.wdMove;  
  6. ThisApplication.Selection.MoveLeft(ref unit, ref count,   
  7.     ref extend);  
  8.    
  9. // Select the 3 words to the right of the insertion point.  
  10. unit = Word.WdUnits.wdWord;  
  11. count = 3;  
  12. extend = Word.WdMovementType.wdExtend;  
  13. ThisApplication.Selection.MoveRight(ref unit, ref count,   
  14.     ref extend);  




 

  • 上下移动时对应的单元类型 MoveUp() MoveDown()
  • wdLine            :行 (缺省)
  • wdParagraph  :段落
  • wdWindow           :窗口
  • wdScreen        :屏幕大小

下面的例子演示了使用上述方法先把插入点向上移动一行,然后选择其后的三个段落。

[csharp] view plaincopy 


  1. // C#  
  2. // Move the insertion point up one line.  
  3. Object unit = Word.WdUnits.wdLine;  
  4. Object count = 1;  
  5. Object extend = Word.WdMovementType.wdMove;  
  6. ThisApplication.Selection.MoveUp(ref unit, ref count, ref extend);  
  7.    
  8. // Select the following 3 paragraphs.  
  9. unit = Word.WdUnits.wdParagraph;  
  10. count = 3;  
  11. extend = Word.WdMovementType.wdMove;  
  12. ThisApplication.Selection.MoveDown(ref unit, ref count,   
  13.   ref extend);  




 

3.2.3 Move Method

使用Move方法将改变指定的range或者selection。

下面的例子将使插入点移动到第三个单词之前

[csharp] view plaincopy 


  1.    
  2. // Use the Move method to move 3 words.  
  3. Obiect unit = Word.WdUnits.wdWord;  
  4. Object count = 3;  
  5. 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)
[csharp] view plaincopy 


  1. public void InsertTextAtSelection()   
  2. {  
  3.   Word.Selection sln = ThisApplication.Selection;  
  4.    
  5.   // Make sure overtype is turned off.  
  6.   ThisApplication.Options.Overtype = false;  
  7.    
  8. //当前的selection对象是否为插入点  
  9. //如果是,那么插入一段字符,然后插入段标记  
  10. if (sln.Type == Word.WdSelectionType.wdSelectionIP )   
  11. {  
  12.     sln.TypeText("Inserting at insertion point. ");  
  13.     sln.TypeParagraph();//插入paragraph mark  
  14. }  
  15.    
  16. //selection对象是否为normal 类型  
  17.   else if (sln.Type == Word.WdSelectionType.wdSelectionNormal )   
  18.   {  
  19.         // 查看ReplaceSelection选项是否开启  
  20. //如果开启,那么摧毁该selection,同时将selection对象修改为插入点类型//且定位到之前的selection区域头部  
  21.         if ( ThisApplication.Options.ReplaceSelection )   
  22.         {  
  23.             Object direction = Word.WdCollapseDirection.wdCollapseStart;  
  24.             sln.Collapse(ref direction);  
  25.         }  
  26.        //插入文本与段落标记  
  27.         sln.TypeText("Inserting before a text block. ");  
  28.         sln.TypeParagraph();  
  29.     }  
  30.     else  
  31.     {  
  32.         // Do nothing.  
  33.     }  
  34. }  
  35. -----------------------------------------------------------------------  



4The 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对象的区域,但是可以在程序中操作。

[csharp] view plaincopy 


  1. // C#  
  2. Object start = 0;  
  3. Object end = 7;  
  4. Word.Range rng = ThisDocument.Range(ref start, ref end);  
  5. rng.Select();  




 

1.1.1  Counting Characters

[csharp] view plaincopy 


  1. // 选择整个文档,并显示字符总数  
  2. Object start = Type.Missing;  
  3. Object end = ThisDocument.Characters.Count;  
  4.    
  5. Word.Range rng = ThisDocument.Range(ref start, ref end);  
  6. rng.Select();  
  7. MessageBox.Show("Characters: " +   
  8.     ThisDocument.Characters.Count.ToString());  




 

1.1.2  Setting Up Ranges

你可以使用Content属性使Range包含整个文档内容

[csharp] view plaincopy 


  1. // C#  
  2. Word.Range rng = ThisDocument.Content;  




下面的例子完成以下功能:

  • 新建一个 Range变量
  • 检查文档中是否至少含有两个句子
  • 使Range的起始点为第二个句子的开头
  • 使Range的结束点为第二个句子的结尾
  • 高亮显示该Range
 
[csharp] view plaincopy 


  1. public void SelectSentence()   
  2. {  
  3.   Word.Range rng;  
  4.    
  5.     if (ThisDocument.Sentences.Count >= 2 )   
  6.     {  
  7.         // Supply a Start and end value for the Range.  
  8.         Object start = ThisDocument.Sentences[2].Start;  
  9.         Object end = ThisDocument.Sentences[2].End;  
  10.         rng = ThisDocument.Range(ref start, ref end);  
  11.         rng.Select();  
  12.     }  
  13. }  




 

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个字符

[csharp] view plaincopy 


  1. // C#  
  2. // Define a range of 7 characters.  
  3. Object start = 0;  
  4. Object end = 7;  
  5. Word.Range rng = ThisDocument.Range(ref start, ref end);  
  6.    
  7. // Move the starting position 7 characters.  
  8. Object unit = Word.WdUnits.wdCharacter;  
  9. Object count = 7;  
  10. rng.MoveStart(ref unit, ref count);  
  11.    
  12. // Move the ending position 7 characters.  
  13. unit = Word.WdUnits.wdCharacter;  
  14. count = 7;  
  15. rng.MoveEnd(ref unit, ref count);  




下图展示了上述代码的移动过程

 

4.3 获得Range的首字符和尾字符

[csharp] view plaincopy 


  1. MessageBox.Show(String.Format("Start: {0}, End: {1}",   
  2.     rng.Start, rng.End), "Range Start and End");  




 

4.4 使用SetRange方法

[csharp] view plaincopy 


  1. // C#  
  2. Word.Range rng;  
  3. Object start = 0;  
  4. Object end = 7;  
  5. rng = ThisDocument.Range(ref start, ref end);  
  6.    
  7. // Reset the existing Range.  
  8. rng.SetRange(ThisDocument.Sentences[2].Start,   
  9.     ThisDocument.Sentences[5].End);  
  10. rng.Select();  




 

4.5 格式化文本

若要给Range指定格式,你首先需要指定一个Range,然后应用格式。

下面的代码演示了如下过程:

1.    选择文档中的第一段,然后设置字号字体以及对齐,

2.    弹出对话框

3.    调用三次Undo方法回退之前的操作

4.    应用Normal IndentStyle然后弹出对话框

5.    调用一次Undo方法然后弹出对话框

[csharp] view plaincopy 


  1. // C#  
  2. public void FormatRangeAndUndo()   
  3. {  
  4.     // Set the Range to the first paragraph.  
  5.     Word.Range rng = ThisDocument.Paragraphs[1].Range;  
  6.    
  7.     // Change the formatting.  
  8.     rng.Font.Size = 14;  
  9.     rng.Font.Name = "Arial";  
  10.     rng.ParagraphFormat.Alignment =  
  11.     Word.WdParagraphAlignment.wdAlignParagraphCenter;  
  12.     rng.Select();  
  13.     MessageBox.Show("Formatted Range", "FormatRangeAndUndo");  
  14.    
  15.     // Undo the three previous actions.  
  16.     Object times = 3;  
  17.     ThisDocument.Undo(ref times);  
  18.     rng.Select();  
  19.     MessageBox.Show("Undo 3 actions", "FormatRangeAndUndo");  
  20.    
  21.     // Apply the Normal Indent style.  
  22.     Object style = "Normal Indent";  
  23.     rng.set_Style(ref style);  
  24.     rng.Select();  
  25.     MessageBox.Show("Normal Indent style applied",   
  26.       "FormatRangeAndUndo");  
  27.    
  28.     // Undo a single action.  
  29.     times = 1;  
  30.     ThisDocument.Undo(ref times);  
  31.     rng.Select();  
  32.     MessageBox.Show("Undo 1 action", "FormatRangeAndUndo");  
  33. }  




 

4.6 插入文本

你可以使用Range对象的Text属性用于向文档中插入文本。下面的代码在文档的开始处插入 “New Text”字符串。然后选择该区域。

[csharp] view plaincopy 


  1. // C#  
  2. string  str = " new Text ";  
  3. Object start = 0;  
  4. Object end = 0;  
  5. Word.Range rng = ThisDocument.Range(ref start, ref end);  
  6. rng.Text = str;  
  7. rng.Select();  




 

4.7 替换文本

[csharp] view plaincopy 


  1. // C#  
  2. start = 0;  
  3. end = 12;  
  4. rng = ThisDocument.Range(ref start, ref end);  
  5. rng.Text = str;  
  6. 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,然后插入新文本。

[csharp] view plaincopy 


  1. // C#  
  2. string  str = " new Text ";  
  3. Word.Range rng = ThisDocument.Paragraphs[1].Range;  
  4. Object direction = Word.WdCollapseDirection.wdCollapseStart;  
  5. rng.Collapse(ref direction);  
  6. rng.Text = str;  
  7. rng.Select();  




 

若使用wdCollapseEnd,即:

[csharp] view plaincopy 


  1. // C#  
  2. Object direction = Word.WdCollapseDirection.wdCollapseEnd;  
  3. rng.Collapse(ref direction);  




结果如下:

 

Tips : Collapse不是很好去翻译,通俗的说,它的功能是:当你的Range对象或者Selection对象包含的内容是一段文字时,使用Collapse()方法可以使 Range或者Selection包含的区域变成原来那段文字的前插入点或者后插入点

 

4.9 Paragraph Mark 段落标记

下面的代码把文档中的前两段相互交换位置

重要例子
[csharp] view plaincopy 


  1. public void ManipulateRangeText()   
  2. {  
  3.     // Retrieve contents of first and second paragraphs  
  4.     string  str1 = ThisDocument.Paragraphs[1].Range.Text;  
  5.     string  str2 = ThisDocument.Paragraphs[2].Range.Text;  
  6.       
  7. // 两个自然段相互交换  
  8.     Word.Range rng1 = ThisDocument.Paragraphs[1].Range;  
  9.     rng1.Text = str2;  
  10.    
  11.     Word.Range rng2 = ThisDocument.Paragraphs[2].Range;  
  12.     rng2.Text = str1;  
  13.    
  14.     // 显示结果  
  15.     rng1.Select();  
  16.     MessageBox.Show(rng1.Text, "ManipulateRangeText");  
  17.     rng2.Select();  
  18. MessageBox.Show(rng2.Text, "ManipulateRangeText");  
  19.     Object unit = Word.WdUnits.wdCharacter;  
  20.     Object count = -1;  
  21.     rng1.MoveEnd(ref unit, ref count);  
  22.     // Write new text for paragraph 1.  
  23. rng1.Text = "new content for paragraph 1.";  
  24.    
  25. rng2.Text = "new content for paragraph 2.";  
  26.     // Pause to display the results.  
  27.     rng1.Select();  
  28.     MessageBox.Show(rng1.Text, "ManipulateRangeText");  
  29.     rng2.Select();  
  30.     MessageBox.Show(rng2.Text, "ManipulateRangeText");  
  31.    
  32. unit = Word.WdUnits.wdCharacter;  
  33.    count = 1;  
  34.    rng1.MoveEnd(ref unit, ref count);  
  35.    // Note that in C#, you must specify   
  36.   // both parameters--it's up to you   
  37.   // to calculate the length of the range.  
  38.   unit = Word.WdUnits.wdCharacter;  
  39.   count = rng2.Characters.Count;  
  40.   rng2.Delete(ref unit, ref count);  
  41.   // C#  
  42.   rng1.Text = str1;  
  43.   // C#  
  44.   rng1.InsertAfter(str2);  
  45.   rng1.Select();  
  46. }  




 

     本文概要性的介绍了word2007的几大对象,主要是一些API的应用。后面将会通过实例,结合VS2010;来实现C#对Word的操作。

本文的PDF版本下载:            C#操作Word2007_v1.0.pdf

另有C#操作Excel的PDF下载:C#操作Excel2007_v1.0.pdf




原标题:c#中操作word文档

关键词:C#

C#
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

网商宝ERP:https://www.ikjzd.com/w/1573152161799069698
3pSeller:https://www.ikjzd.com/w/1573152172674555905
法瑞儿(3Suisses):https://www.ikjzd.com/w/1573152173979328513
4PNT(四方网络科技):https://www.ikjzd.com/w/1573152178701770753
4psite:https://www.ikjzd.com/w/1573152179469672450
倍速社区:https://www.ikjzd.com/w/1573152183848525825
五月电商盛宴:节假日营销策略解析与商机揭秘 :https://www.kjdsnews.com/a/1842215.html
2023年意大利在线销售额超800亿欧元,增长27.14%:https://www.kjdsnews.com/a/1842216.html
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流