Word對(duì)象模型 (.Net Perspective)
本文首要針對(duì)在Visual Studio中應(yīng)用C# 開辟關(guān)于Word的應(yīng)用法度
起原:Understandingthe Word Object Model a .NET Developer""s Perspective
五大對(duì)象
Application :代表Microsoft Word應(yīng)用法度本身
Document :代表一個(gè)Word文檔
Selection :代表當(dāng)前選中的區(qū)域(高亮),,沒有選中區(qū)域時(shí)代表光標(biāo)點(diǎn)
Bookmarks :書簽
Range :代表一塊區(qū)域,與Selection類似,,不過一般不成見
下面看一下Word的對(duì)象布局圖:
OK,,下面是對(duì)上述幾大對(duì)象的根蒂根基特點(diǎn)的描述,讓我們對(duì)它們有一些根蒂根基的熟悉,。
l Application是Document和Selection的基類,。經(jīng)由過程Application的屬性和辦法,我們可以把握Word的大景象,。
l Document代表一個(gè)Word文檔,,當(dāng)你新建一個(gè)Word文檔或者打開一個(gè)已有的Word文檔,你將創(chuàng)建一個(gè)Document對(duì)象,,該對(duì)象被參加到Words Documents Collection中,。擁有核心的Document稱為ActiveDocument,可以經(jīng)由過程Application對(duì)象的ActiveDocument屬性獲合適前文檔對(duì)象
l Selection代表當(dāng)前選中的區(qū)域,,它凡是是高亮顯示的(例如,你要改變一段文字的字體,,你起首得選 中這段文字,,那么選中的這塊區(qū)域就是當(dāng)前文檔的Selection對(duì)象所包含的區(qū)域)
l Range對(duì)象也代表文檔中的一塊區(qū)域,它具有以下特點(diǎn)
- 包含一個(gè)肇端地位和一個(gè)停止地位
- 它可以包含光標(biāo)點(diǎn),,一段文本或者全部文檔
- 它包含空格,,tab以及paragraph marks
- 它可所以當(dāng)前選中的區(qū)域,當(dāng)然也可以不是當(dāng)前選中區(qū)域
- 它被動(dòng)態(tài)創(chuàng)建
- 當(dāng)你在一個(gè)Range的末尾插入文本,,這將擴(kuò)大該Range
l Bookmark對(duì)象也代表一塊區(qū)域,,一般應(yīng)用Bookmark來標(biāo)識(shí)表記標(biāo)幟文檔中的地位,,它有如下特點(diǎn)
- 書簽一般有名字
- Saved with the document,且文檔封閉了之后書簽持續(xù)存在
- 書簽凡是是隱蔽的,,但也可以經(jīng)由過程代碼設(shè)置其為可見
---------------------------------------------------------------------------------------------
下面分別介紹5大對(duì)象:
1. The Application Object
經(jīng)由過程Application對(duì)象,,你可以接見Word的所有對(duì)象以及Collections。
參考更多:MSDN-Word2007-Application Object
1.1 Application對(duì)象的屬性(只介紹項(xiàng)目組,,完全內(nèi)容請(qǐng)參看MSDN)
l ActiveWindow 返回一個(gè)Window對(duì)象默示擁有核心的窗口
[csharp] view plaincopyprint,?
-
- public void CreateNewWindowAndTile()
- {
-
- Word.Window wnd = ThisApplication.ActiveWindow.NewWindow();
-
-
- 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 當(dāng)前活動(dòng)文檔對(duì)象
l ActivePrinter 當(dāng)前活動(dòng)打印機(jī)
l ActiveWindow 當(dāng)前活動(dòng)窗口
l Caption 文檔題目
[csharp] view plaincopyprint,?
-
- public void SetApplicationCaption()
- {
-
- ThisApplication.Caption = "My New Caption";
- }
l CapsLock 返回大小寫鎖定鍵狀況
[csharp] view plaincopyprint?
-
- public void CapsLockOn()
- {
- MessageBox.Show(ThisApplication.CapsLock.ToString());
- }
l DisplayAlerts 用于設(shè)置在代碼容許時(shí)如何處理懲罰警告,,它有三種選項(xiàng):
1.wdAlertsAll 顯示所有消息和警告(默認(rèn))
2.wdAlertsMessageBox 僅顯示消息框
3.wdAlertsNone 忽視任何警告
下面是該屬性的常見用法:
[csharp] view plaincopyprint,?
-
- public void DisplayAlerts()
- {
-
- try
- {
- ThisApplication.DisplayAlerts = Word.WdAlertLevel.wdAlertsNone;
-
-
-
- }
- catch (Exception ex)
- {
-
-
- }
- finally
- {
-
- ThisApplication.DisplayAlerts = Word.WdAlertLevel.wdAlertsAll;
- }
- }
l DisplayStatusBar 可以讀/寫;用于默示是否顯示狀況欄
[csharp] view plaincopyprint,?
-
- public void ToggleStatusBar()
- {
-
- bool bln = ThisApplication.DisplayStatusBar;
- ThisApplication.DisplayStatusBar = !bln;
- }
l Path 返回當(dāng)前應(yīng)用法度的路徑
[csharp] view plaincopyprint,?
-
- MessageBox.Show(ThisApplication.Path);
l Selection 只讀對(duì)象,默示當(dāng)前選擇的區(qū)域(也可以默示光標(biāo)點(diǎn)地位)
l UserName 讀或?qū)懹脩裘?/P>
[csharp] view plaincopyprint,?
-
- public void ChangeUserName()
- {
- string str = ThisApplication.UserName;
- MessageBox.Show(str);
-
-
- ThisApplication.UserName = "Dudley";
- MessageBox.Show(ThisApplication.UserName);
-
- ThisApplication.UserName = str;
- }
l Visible 只有為true時(shí)才可見
[csharp] view plaincopyprint,?
-
- try
- {
- ThisApplication.Visible = false;
-
- }
- catch (Exception ex)
- {
-
- }
- finally
- {
- ThisApplication.Visible = true;
- }
1.2 Application對(duì)象的辦法
l CheckSpelling 搜檢拼寫
l Help 彈出幫助對(duì)話框,,有三種:WdHelp,,WdHelpAbout,WdHelpSearch
[csharp] view plaincopyprint,?
-
- public void DisplayHelpAbout()
- {
- Object value = Word.WdHelpType.wdHelpAbout;
- ThisApplication.Help(ref value);
- }
l Move 移動(dòng)窗口
l Resize 改變窗口大小
[csharp] view plaincopyprint,?
-
- public void MoveAndResizeWindow()
- {
-
-
- ThisApplication.ActiveWindow.WindowState =
- Word.WdWindowState.wdWindowStateNormal;
-
-
- ThisApplication.Move(0, 0);
-
-
- ThisApplication.Resize(300,, 600);
- }
l Quit 退出Word,,可以帶參數(shù)WdSaveOptions:三個(gè)可選值分別是:
1.wdSaveChanges
2.wdPromptToSaveChanges
3.wdDoNotSaveChanges
[csharp] view plaincopyprint?
-
-
- Object saveChanges = Word.WdSaveOptions.wdSaveChanges;
- Object originalFormat = Type.Missing;
- Object routeDocument = Type.Missing;
- ThisApplication.Quit( ref saveChanges,,
- ref originalFormat,,
- ref routeDocument);
-
-
- saveChanges = Word.WdSaveOptions.wdPromptToSaveChanges;
- originalFormat = Type.Missing;
- routeDocument = Type.Missing;
- ThisApplication.Quit( ref saveChanges,
- ref originalFormat,,
- ref routeDocument);
-
-
- saveChanges = Word.WdSaveOptions.wdDoNotSaveChanges;
- originalFormat = Type.Missing;
- routeDocument = Type.Missing;
- ThisApplication.Quit( ref saveChanges,,
- ref originalFormat,
- ref routeDocument);
2. The Document Object
應(yīng)用Document對(duì)象容許你對(duì)一個(gè)文檔進(jìn)行操縱,,同時(shí)因?yàn)镈ocuments Collection的存在,,你可以操縱所有已經(jīng)打開的文檔,。
參考更多:MSDN-Word2007-Document Object
2.1 Document Object Collections
一個(gè)文檔可以包含一下幾類對(duì)象:
- l Characters
- l Words
- l Sentences
- l Paragraphs
- l Sections
- l Headers/Footers
2.2 引用文檔
你可以引用一個(gè)Documents Collection中的Document對(duì)象。引用的辦法是應(yīng)用索引(1-based),,例如,,如下代碼引用了collection中的第一個(gè)文檔
[csharp] view plaincopyprint?
-
- Word.Document doc = (Word.Document) ThisApplication.Documents[1];
當(dāng)然,,你也可以經(jīng)由過程文檔的名字來引用它
[csharp] view plaincopyprint,?
-
- Word.Document doc =
- (Word.Document) ThisApplication.Documents["MyDoc.doc"];
2.3 打開,封閉與新建文檔
l Add 新建word文檔
[csharp] view plaincopyprint,?
-
-
- 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文檔
[csharp] view plaincopyprint,?
-
- 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文檔
[csharp] view plaincopyprint?
-
- Object noPrompt = true;
- Object originalFormat = Type.Missing;
- ThisApplication.Documents.Save(ref noPrompt,, ref originalFormat);
-
-
- ThisApplication.ActiveDocument.Save();
-
[csharp] view plaincopyprint,?
-
- Object file = "MyNewDocument.doc";
- ThisApplication.Documents.get_Item(ref file).Save();
l SaveAs 另存為
[csharp] view plaincopyprint?
-
-
-
-
-
- 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 LineBreaks = 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 LineBreaks,,
- ref allowSubstitutions, ref lineEnding,, ref addBiDiMarks);
l Close 封閉word文檔
[csharp] view plaincopyprint,?
-
- Object saveChanges = Word.WdSaveOptions.wdSaveChanges;
- Object originalFormat = Type.Missing;
- Object routeDocument = Type.Missing;
- ThisApplication.Documents.Close(ref saveChanges,
- ref originalFormat,,
- ref routeDocument);
[csharp] view plaincopyprint,?
-
- Object saveChanges = Word.WdSaveOptions.wdDoNotSaveChanges;
- Object originalFormat = Type.Missing;
- Object routeDocument = Type.Missing;
- ThisDocument.Close( ref saveChanges,
- ref originalFormat,,
- ref routeDocument);
-
-
- 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 實(shí)例:遍歷DocumentsCollection
[csharp] view plaincopyprint,?
-
- public void SaveUnsavedDocuments()
- {
-
- string str;
- StringWriter sw = new StringWriter();
-
- foreach (Word.Document doc in ThisApplication.Documents)
- {
- if (!doc.Saved )
- {
-
- 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對(duì)象代表當(dāng)前選擇的area。在word應(yīng)用法度中,,假如你要讓一段字符變成黑體,,你必須起首選擇該段文字,然后應(yīng)用樣式,。在代碼中也是同樣的事理,,你要起首定義ion的區(qū)域然掉隊(duì)行操縱。你可以應(yīng)用Selection對(duì)象在文檔中進(jìn)行選擇,,格局化,,操縱,添加文本等,。
Selection對(duì)象是始終存在的,,若是當(dāng)前沒有選擇任何器材,那么它代表一個(gè)ion point,。是以,,在操縱Seleciton之前知道它包含的內(nèi)容是很是首要的。
Tips: Selection對(duì)象與Range對(duì)象有很多成員是類似的,,它們之間的差別是Selection對(duì)象指的是現(xiàn)其實(shí)圖形界面的區(qū)域,,而Range對(duì)象代表的區(qū)域是不成見的(當(dāng)然經(jīng)由過程調(diào)用辦法可以使其可見)
1.1 Using the Type Property
Selection的類型有很多。比如,你要對(duì)一張表格的一列進(jìn)行操縱,,你應(yīng)當(dāng)確保該列已經(jīng)ed,,不然會(huì)呈現(xiàn)運(yùn)行時(shí)錯(cuò)誤。
可以經(jīng)由過程Selection對(duì)象的 Type屬性獲取你須要的信息,,Type屬性包含一個(gè)WdSelectionType的列舉類型成員,。它有如下幾個(gè)值:
- wdSelectionBlock
- wdSelectionColumn
- wdSelectionFrame
- wdSelectionInlineShape 默示一幅圖片
- wdSelectionIP 默示插入點(diǎn)(ion point)
- wdSelectionNormal 默示選中的文本或者文本和其他對(duì)象的組合
- wdNoSelection
- wdSelectionRow
- wdSelectionShape
下面是Type屬性的應(yīng)用例子
[csharp] view plaincopyprint?
-
- 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 = "ion point";
- break;
- case Word.WdSelectionType.wdSelectionNormal:
- str = "normal text";
- break;
- case Word.WdSelectionType.wdNoSelection:
- str = "no ion";
- 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
在應(yīng)用Word時(shí),我們知道,,按下鍵盤的HOME鍵將使光標(biāo)移動(dòng)到光標(biāo)地點(diǎn)行的行首,按下END鍵將使光標(biāo)移動(dòng)到行尾,。在代碼中,,可以應(yīng)用模仿按鍵的辦法將改變ion。請(qǐng)看下面兩個(gè)函數(shù):
HomeKey( [Unit] ,, [Extend] ) : 模仿按下HOME鍵
EndKey( [Unit] ,, [Extend] ) :模仿按下END鍵
上方的兩個(gè)函數(shù)中,參數(shù)Unit有一下可選值(wdUnit類型):
l Wdline 移動(dòng)到一行的開端或停止地位(缺省值)
l WdStory 移動(dòng)到文檔的開端或停止地位
l WdColumn 移動(dòng)到一列的開端或停止地位(僅針對(duì)表格)
l WdRow 移動(dòng)到一行的開端或停止地位(僅正對(duì)表格)
參數(shù)Extend的可選值(WdMovementType類型):
l WdMove 移動(dòng)ion
l WdExtend 擴(kuò)大ion,。舉例申明:推敲一個(gè)場景,,當(dāng)前選擇了一行,然后調(diào)用HomeKey辦法,,傳入?yún)?shù)wdStory以及wdExtend,,那么該行將不被包含在新ion對(duì)象中,同樣的景象若是調(diào)用EndKey辦法,,那么該行將會(huì)包含在新ion對(duì)象中,。
下面的示例代碼演示了:移動(dòng)ion point到文檔開端出,然后應(yīng)用EndKey辦法選中全部文檔:
[csharp] view plaincopyprint,?
-
-
-
- Object unit = Word.WdUnits.wdStory;
- Object extend = Word.WdMovementType.wdMove;
- ThisApplication.Selection.HomeKey(ref unit,, ref extend);
-
-
- unit = Word.WdUnits.wdStory;
- extend = Word.WdMovementType.wdExtend;
- ThisApplication.Selection.EndKey(ref unit, ref extend);
1.2.2 Arrow Key Method
既然可以模仿HOME,,END鍵,,那么當(dāng)然也可以模仿按下標(biāo)的目標(biāo)鍵。Word供給如下四個(gè)辦法,,此中Count參數(shù)代表移動(dòng)幾許個(gè)Unit,。
- MoveLeft([Unit], [Count],, [Extend])
- MoveRight([Unit],, [Count],, [Extend])
- MoveUp([Unit], [Count],, [Extend])
- MoveDown([Unit],, [Count], [Extend])
此中,,Extend參數(shù)應(yīng)用的是與END,HOME雷同的列舉類型變量,,它包含兩個(gè)可選值:wdMove,,wdExtend.
而移動(dòng)單位(Unit)類型與前面的有所不合,并且針對(duì)閣下移動(dòng)和高低移動(dòng)有所區(qū)分,。
- 閣下移動(dòng)時(shí)對(duì)應(yīng)的單位類型 MoveLeft() MoveRight()
- wdCharacter: 字符(缺?。?/LI>
- wdWord: 單詞
- wdCell: 單位格(僅對(duì)表格)
- wdSentence: 句子
下面的代碼演示了:向左移動(dòng)插入點(diǎn)三個(gè)字符,然后選擇插入點(diǎn)右邊的三個(gè)單詞
[csharp] view plaincopyprint,?
-
-
- Object unit = Word.WdUnits.wdCharacter;
- Object count = 3;
- Object extend = Word.WdMovementType.wdMove;
- ThisApplication.Selection.MoveLeft(ref unit,, ref count,
- ref extend);
-
-
- unit = Word.WdUnits.wdWord;
- count = 3;
- extend = Word.WdMovementType.wdExtend;
- ThisApplication.Selection.MoveRight(ref unit,, ref count,,
- ref extend);
- 高低移動(dòng)時(shí)對(duì)應(yīng)的單位類型 MoveUp() MoveDown()
- wdLine :行 (缺省)
- wdParagraph :段落
- wdWindow :窗口
- wdScreen :屏幕大小
下面的例子演示了應(yīng)用上述辦法先把插入點(diǎn)向上移動(dòng)一行,,然后選擇厥后的三個(gè)段落,。
[csharp] view plaincopyprint?
-
-
- Object unit = Word.WdUnits.wdLine;
- Object count = 1;
- Object extend = Word.WdMovementType.wdMove;
- ThisApplication.Selection.MoveUp(ref unit,, ref count,, ref extend);
-
-
- unit = Word.WdUnits.wdParagraph;
- count = 3;
- extend = Word.WdMovementType.wdMove;
- ThisApplication.Selection.MoveDown(ref unit, ref count,,
- ref extend);
3.2.3 Move Method
應(yīng)用Move辦法將改變指定的range或者ion,。
下面的例子將使插入點(diǎn)移動(dòng)到第三個(gè)單詞之前
[csharp] view plaincopyprint?
-
-
- Obiect unit = Word.WdUnits.wdWord;
- Object count = 3;
- ThisApplication.Selection.Move(ref unit,, ref count);
3.2.4 Inserting Text
最簡單的在文檔中插入文本的辦法是應(yīng)用Selection對(duì)象的TypeText辦法,。TypeText辦法的行動(dòng)由用戶的選擇決意。下面這個(gè)例子就應(yīng)用了一個(gè)叫做 overtype 的選項(xiàng),。該選項(xiàng)若是被打開,,那么插入字符將導(dǎo)致插入點(diǎn)后面的文本被覆蓋。
----------------------------------------------------------------------------
首要的例子 演示如何插入文本
(若ion類型不是ion point或者 a block of text ,,那么下面的代碼do nothing)
[csharp] view plaincopyprint,?
- public void InsertTextAtSelection()
- {
- Word.Selection sln = ThisApplication.Selection;
-
-
- ThisApplication.Options.Overtype = false;
-
-
-
- if (sln.Type == Word.WdSelectionType.wdSelectionIP )
- {
- sln.TypeText("Inserting at ion point. ");
- sln.TypeParagraph();
- }
-
-
- else if (sln.Type == Word.WdSelectionType.wdSelectionNormal )
- {
-
-
- if ( ThisApplication.Options.ReplaceSelection )
- {
- Object direction = Word.WdCollapseDirection.wdCollapseStart;
- sln.Collapse(ref direction);
- }
-
- sln.TypeText("Inserting before a text block. ");
- sln.TypeParagraph();
- }
- else
- {
-
- }
- }
- -----------------------------------------------------------------------
4. The Range Object
Range對(duì)象也代表一個(gè)區(qū)域。與應(yīng)用Selection相斗勁,,Range的上風(fēng)在于
l 履行給定任務(wù)須要較少的代碼
l 不須要改變當(dāng)前文檔的選中區(qū)域(donot have to change the highlighting)
l Has greater capabilities
4.1 定義并選擇一個(gè)Range
下面的代碼新建一個(gè)Range對(duì)象,,并選擇文檔的前7個(gè)字符,包含non-printing字符,,然后應(yīng)用Select辦法是Range可見(即高亮顯示),。若是不應(yīng)用Select辦法,在Word界面中你將看不到Range對(duì)象的區(qū)域,,然則可以在法度中操縱,。
[csharp] view plaincopyprint?
-
- Object start = 0;
- Object end = 7;
- Word.Range rng = ThisDocument.Range(ref start,, ref end);
- rng.Select();
1.1.1 Counting Characters
[csharp] view plaincopyprint,?
-
- 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
你可以應(yīng)用Content屬性使Range包含全部文檔內(nèi)容
[csharp] view plaincopyprint,?
-
- Word.Range rng = ThisDocument.Content;
下面的例子完成以下功能:
- 新建一個(gè) Range變量
- 搜檢文檔中是否至少含有兩個(gè)句子
- 使Range的肇端點(diǎn)為第二個(gè)句子的開首
- 使Range的停止點(diǎn)為第二個(gè)句子的結(jié)尾
- 高亮顯示該Range
[csharp] view plaincopyprint?
- public void SelectSentence()
- {
- Word.Range rng;
-
- if (ThisDocument.Sentences.Count >= 2 )
- {
-
- Object start = ThisDocument.Sentences[2].Start;
- Object end = ThisDocument.Sentences[2].End;
- rng = ThisDocument.Range(ref start,, ref end);
- rng.Select();
- }
- }
4.2 擴(kuò)大Range
定義Range對(duì)象后,,可以應(yīng)用MoveStart和MoveEnd辦法擴(kuò)大它的局限。這兩個(gè)函數(shù)應(yīng)用兩個(gè)雷同的參數(shù):Unit與Count,。此中Unit參數(shù)是WdUnits類型,,它有如下可選值:
- wdCharacter
- wdWord
- wdSentence
- wdParagraph
- wdSection
- wdStory
- wdCell
- wdColumn
- wdRow
- wdTable
下面的例子演示了:定義一個(gè)Range包含文檔的前7個(gè)字符,然后移動(dòng)其開端點(diǎn)7個(gè)字符長度,,于是成果是本來的Range變成了一個(gè)ion point,;然后應(yīng)用MoveEnd辦法使其停止點(diǎn)移動(dòng)7個(gè)字符
[csharp] view plaincopyprint?
-
-
- Object start = 0;
- Object end = 7;
- Word.Range rng = ThisDocument.Range(ref start,, ref end);
-
-
- Object unit = Word.WdUnits.wdCharacter;
- Object count = 7;
- rng.MoveStart(ref unit,, ref count);
-
-
- unit = Word.WdUnits.wdCharacter;
- count = 7;
- rng.MoveEnd(ref unit, ref count);
下圖顯現(xiàn)了上述代碼的移動(dòng)過程
4.3 獲得Range的首字符和尾字符
[csharp] view plaincopyprint,?
- MessageBox.Show(String.Format("Start: {0},, End: {1}",
- rng.Start,, rng.End),, "Range Start and End");
4.4 應(yīng)用SetRange辦法
[csharp] view plaincopyprint?
-
- Word.Range rng;
- Object start = 0;
- Object end = 7;
- rng = ThisDocument.Range(ref start,, ref end);
-
-
- rng.SetRange(ThisDocument.Sentences[2].Start,,
- ThisDocument.Sentences[5].End);
- rng.Select();
4.5 格局化文本
若要給Range指定格局,你起首須要指定一個(gè)Range,,然后應(yīng)用格局,。
下面的代碼演示了如下過程:
1. 選擇文檔中的第一段,,然后設(shè)置字號(hào)字體以及對(duì)齊,
2. 彈出對(duì)話框
3. 調(diào)用三次Undo辦法回退之前的操縱
4. 應(yīng)用Normal IndentStyle然后彈出對(duì)話框
5. 調(diào)用一次Undo辦法然后彈出對(duì)話框
[csharp] view plaincopyprint,?
-
- public void FormatRangeAndUndo()
- {
-
- Word.Range rng = ThisDocument.Paragraphs[1].Range;
-
-
- rng.Font.Size = 14;
- rng.Font.Name = "Arial";
- rng.ParagraphFormat.Alignment =
- Word.WdParagraphAlignment.wdAlignParagraphCenter;
- rng.Select();
- MessageBox.Show("Formatted Range",, "FormatRangeAndUndo");
-
-
- Object times = 3;
- ThisDocument.Undo(ref times);
- rng.Select();
- MessageBox.Show("Undo 3 actions", "FormatRangeAndUndo");
-
-
- Object style = "Normal Indent";
- rng.set_Style(ref style);
- rng.Select();
- MessageBox.Show("Normal Indent style applied",,
- "FormatRangeAndUndo");
-
-
- times = 1;
- ThisDocument.Undo(ref times);
- rng.Select();
- MessageBox.Show("Undo 1 action",, "FormatRangeAndUndo");
- }
4.6 插入文本
你可以應(yīng)用Range對(duì)象的Text屬性用于向文檔中插入文本。下面的代碼在文檔的開端處插入 “New Text”字符串,。然后選擇該區(qū)域,。
[csharp] view plaincopyprint?
-
- 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 調(diào)換文本
[csharp] view plaincopyprint?
-
- start = 0;
- end = 12;
- rng = ThisDocument.Range(ref start,, ref end);
- rng.Text = str;
- rng.Select();
4.8 Collapsing a Range of Selection
當(dāng)應(yīng)用Range對(duì)象或者Selection對(duì)象時(shí),,有可能須要在一段文字前插入文本的同時(shí)又不想覆蓋本來的文本,Range對(duì)象和Selection對(duì)象都有Collapse辦法,,該辦法應(yīng)用了兩個(gè)列舉值:
WdCollapseStart:Collapses the ion to thebeginning of itself
WdCollapseEnd:Collapsesthe ion to the end of itself
下面的例子起首創(chuàng)建一個(gè)Range,,然后使其包含文檔的第一段,然后應(yīng)用wdCollapseStart列舉值Collapse該Range,,然后插入新文本,。
[csharp] view plaincopyprint?
-
- 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();
若應(yīng)用wdCollapseEnd,,即:
[csharp] view plaincopyprint,?
-
- Object direction = Word.WdCollapseDirection.wdCollapseEnd;
- rng.Collapse(ref direction);
成果如下:
Tips : Collapse不是很好去翻譯,通俗的說,,它的功能是:當(dāng)你的Range對(duì)象或者Selection對(duì)象包含的內(nèi)容是一段文字時(shí),,應(yīng)用Collapse()辦法可以使 Range或者Selection包含的區(qū)域變成本來那段文字的前插入點(diǎn)或者后插入點(diǎn)
4.9 Paragraph Mark 段落標(biāo)識(shí)表記標(biāo)幟
下面的代碼把文檔中的前兩段彼此互換地位
首要例子
[csharp] view plaincopyprint?
- public void ManipulateRangeText()
- {
-
- 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);
-
- rng1.Text = "new content for paragraph 1.";
-
- rng2.Text = "new content for paragraph 2.";
-
- 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);
-
-
-
- unit = Word.WdUnits.wdCharacter;
- count = rng2.Characters.Count;
- rng2.Delete(ref unit,, ref count);
-
- rng1.Text = str1;
-
- rng1.InsertAfter(str2);
- rng1.Select();
- }
本文概要性的介紹了word2007的幾大對(duì)象,主如果一些API的應(yīng)用,。后面將會(huì)經(jīng)由過程實(shí)例,,連絡(luò)VS2010,;來實(shí)現(xiàn)C#對(duì)Word的操縱。