C#操作Word (1)Word对象模型

Word对象模型 一点课堂(多岸学院) Word对象模型 一、开发环境布置 C#中添加对Word的支持,只需添加对Microsoft.Office.Interop.Word的命名空间,如下图所示,右键点击“引用”,在弹出的“添加引用”对话框中选中COM标签页,找到“Microsoft Word 12.0 Object Library”。点击确定按钮后,可在引用中添加显示名称为Microsoft.Office.Interop.Word的... 阅读详情
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);
}


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

一个文档可以包含一下几类对象:

  • 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

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


C#在WinForm中操作Word文档的实现 Word应用程序对象是Microsoft Office Word应用程序的顶级对象,它可以被用来访问Word中的所有可用对象,比如文档、范围、视图等。它类似于一个容器,内含应用程序的所有文档实例和其他相关对象。在.NET环境下,Word对象模型暴露于Microsoft.Office.Interop.Word命名空间中,使C#开发者能够方便地调用和操作。通过操作Word应用程序对象,开发者可以编程实现文档的创建、打开、保存、打印以及更多的高级功能,例如更改文档结构、插入图形元素、设置文本格式等。 阅读详情

相关推荐

C#中操作Word组件的完全指南

在C#开发中,利用组件对象模型(Component Object Model, COM)组件可以扩展应用程序的功能。通过封装遗留代码或利用现成的第三方库,开发人员可以将这些COM组件集成到C#应用程序中,以实现丰富的交互功能。

weixin_32099703的博客 1051

Word对象模型 (.Net Perspective)

Word对象模型(.Net Perspective)   五大对象Application:代表Microsoft Word应用程序本身   是Document和Selection的基类。通过Application的属性和方法,我们可以控制Word的大环境。Document:代表一个Word文档   当你新建一个Word文档或者打开一个已有的Word文档,你将创建一个Document对象,该对象被...

nhlouger的博客 1901

C#操作Word(word对象模型)

本文详细介绍了Word对象模型以及如何使用C#开发关于Word的应用程序

Word Vba技巧总结

确定文本是否被选定:If Selection.Type = wdSelectionIP Then MsgBox "Nothing is selected"word中选择单元格:Selection.SelectCell移动到选定内容之后:Selection.Collapse Direction:=wdCollapseEnd定位到Word中最后一行:Selection.EndKey unit:=wdS

飞翔的专栏 5679

变焦跟踪理论基础(如何在变焦过程中保持清晰)

如何在整个变焦过程中一直保持图像的清晰度或焦点是变焦跟踪的主要挑战。 当用户在缩放跟踪的情况下改变缩放时,设备保持对焦。 然而,在没有变焦跟踪的情况下,图像变得失焦,图像在变焦跟踪后由于自动对焦(AF)算法才最终对焦。...................................................

ChenYX的博客 20万+

【深度排查】VScode 远程 SSH 连接失败:从网络握手到服务部署的全链路诊断指南

本文详细解析了VScode远程SSH连接失败的常见原因及解决方案,从基础网络排查到SSH服务配置,再到VScode特有的问题处理。特别针对Ubuntu和TrueNAS系统提供了具体配置建议,帮助开发者快速解决'Could not establish connection'等连接问题,提升远程开发效率。

weixin_30301449的博客 447

C#中操作Word(1)—— word对象模型介绍

一、开发环境布置          C#中添加对Word的支持,只需添加对Microsoft.Office.Interop.Word的命名空间,如下图所示,右键点击“引用”,在弹出的“添加引用”对话框中选中COM标签页,找到“Microsoft Word 12.0 Object Library”。           点击确定按钮后,可在引用中添加显示名称为Microsoft.Office.

Hyman的博客 4478

MFC 修改CheckBox的文本颜色方法

设置主题 这一步是必须的,不可省略。 BOOL CMFCApplication1Dlg::OnInitDialog() { CDialogEx::OnInitDialog(); // 设置此对话框的图标。 当应用程序主窗口不是对话框时,框架将自动 // 执行此操作 SetIcon(m_hIcon, TRUE); // 设置大图标 SetIcon(m_hIcon, FALSE); // 设置小图标 // TODO: 在此添加额外的初始化代码 // 设置主题 HWND

Kim的博客 2249

快速上手之 C#操作WORD对象模型

想当年省计算机一级考了60飘过,暗自窃喜。 如今要考虑它是怎么给我判了个60分。 当年不会做Excel题,OUTLOOK题,IE题。 如今要搞清楚它判分的逻辑是什么。 两年如此大的差距,晕晕的开始没有头绪,后来... 矫情一番,收。什么是WORD对象模型?

周洲 (Julie) 2837

YOLOv8实例分割实战:从LabelMe标注到模型训练全流程(附完整代码)

本文详细介绍了YOLOv8实例分割的完整实战流程,涵盖从使用LabelMe进行数据标注、格式转换,到构建数据集、配置参数并完成模型训练的全过程。文章提供了详尽的代码示例和常见问题解决方案,旨在帮助开发者高效掌握YOLOv8实例分割技术,快速应用于实际项目。

java5的博客 816

手把手教你用TLP350驱动IGBT:光耦隔离驱动电路完整设计教程

本文详细介绍了如何使用TLP350光耦隔离驱动电路设计IGBT驱动方案。从TLP350芯片特性分析到驱动电路架构设计,包括信号调理、自举电源和栅极控制网络,再到PCB布局优化和保护电路设计,提供了完整的实战指南。通过实测波形分析和故障排查,帮助工程师快速掌握IGBT驱动电路的设计要点和进阶技巧。

weixin_30566063的博客 832

C# 操作Word

C#操作Word

c_c33的博客 5193

你的OLED屏和MPU6050为啥通信失败?从IIC的7位地址冲突讲起

本文深入解析OLED屏与MPU6050传感器在I2C总线上的通信故障,重点探讨7位地址冲突问题。通过分析I2C协议中的地址分配机制,提供硬件调整和软件调试的完整解决方案,帮助开发者有效排查和解决设备无响应问题。

weixin_26876073的博客 151

C#操作Word的超详细总结

本文中用C#来操作Word,包括: 创建Word; 插入文字,选择文字,编辑文字的字号、粗细、颜色、下划线等; 设置段落的首行缩进、行距; 设置页面页边距和纸张大小; 设置页眉、页码; 插入图片,设置图片宽高以及给图片添加标题; 插入表格,格式化表格,往表格中插入数据; 保存Word,打印Word; 重新打开Word等。 Visual studio版本:Visual...

ZeroCode 8235

vscode+latex+bib文献管理

下载vscode 安装插件`` 在setting.json中配置 在.tex文件中编写论文内容,然后左侧TEX侧边栏中编译,如下图所示,中文用xelatex,英文用pdflatex;编译成功后,就可以查看pdf版本的论文了,我一般在浏览器显示。 涉及到文献编译:XXX.bib中存储文献管理内容;XXX.tex是文章内容,使用xelatex编译后会生成XXX.aux,ctrl+⋅ctrl+·ctrl+⋅打开命令行窗口,输入bibtex XXX(可以对aux文件进行编译,不需要加后缀),然后再xelatex.

小卜妞的博客 2548

运用c# 对Word进行操作总结(一)创建Word文档

 在医疗管理系统中为保存患者的体检和治疗记录,方便以后的医生或其他人查看。当把数据保存到数据库中,需要新建很多的字段,而且操作很繁琐,于是想到网页的信息创建到一个word文本中,在显示的时,可以在线打开word,也可以把word转换成html标签显示。 这样使用word代替网页的原因有:   第一:网页生成数学公式和特殊符号存储和显示比较麻烦(如何操作word生成数学公式,有待测试)   第二...

qq_41991908的博客 7490

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

C#操作Word方法详细大汇总

本文中用C#来操作Word,包括: 创建Word; 插入文字,选择文字,编辑文字的字号、粗细、颜色、下划线等; 设置段落的首行缩进、行距; 设置页面页边距和纸张大小; 设置页眉、页码; 插入图片,设置图片宽高以及给图片添加标题; 插入表格,格式化表格,往表格中插入数据; 保存Word,打印Word; 重新打开Word等。 Visual studio版本:Visual Studio 2012(201...

T643685558的博客 5762

最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版

Part-E1-SDIO-Specification-Ver4.00-Final-120220.pdf:最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版,包括SDIO 接口的外设,SDIO 接口官方协议等。

汉书HE8,好用的汇编代码编写工具

汉书HE8,好用的汇编代码编写工具早期编写汇编代码所用功能强大

上一篇: C#操作Excel(2)-- 打开-读取Excel文档
下一篇: C#操作Word (2)-- 打开&关闭Word文档
ruby97
博客等级 码龄15年 626粉丝 23原创
评论 8
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值