參考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
五大對象
Application :代表Microsoft Word應用程序本身
Document :代表一個Word文檔
Selection :代表當前選中的區域(高亮),沒有選中區域時代表光標點
Bookmarks :書簽
Range :代表一塊區域,與Selection類似,不過一般不可見
下面看一下Word的對象結構圖:

OK,下面是對上述幾大對象的基本特性的描述,讓我們對它們有一些基本的認識。
Application是Document和Selection的基類。通過Application的屬性和方法,我們可以控制Word的大環境。
Document代表一個Word文檔,當你新建一個Word文檔或者打開一個已有的Word文檔,你將創建一個Document對象,該對象被加入到Words Documents Collection中。擁有焦點的Document稱為ActiveDocument,可以通過Application對象的ActiveDocument屬性獲得當前文檔對象
Selection代表當前選中的區域,它通常是高亮顯示的(例如,你要改變一段文字的字體,你首先得選 中這段文字,那么選中的這塊區域就是當前文檔的Selection對象所包含的區域)
Range對象也代表文檔中的一塊區域,它具有以下特點
- 包含一個起始位置和一個結束位置
- 它可以包含光標點,一段文本或者整個文檔
- 它包含空格,tab以及paragraph marks
- 它可以是當前選中的區域,當然也可以不是當前選中區域
- 它被動態創建
- 當你在一個Range的末尾插入文本,這將擴展該Range
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
