Working with Documents

The Documents collection, available from the Application object's Documents property, contains a collection of Document objects currently open in Word. It also has methods used to access a Document in the collection, create a new document, open an existing document, close all the documents, and save all the documents.

Iterating over the Open Documents

The documents collection can be iterated over using the foreach keyword in C#. Listing 8-18 shows a simple example of iterating over the open documents in Word and printing the name of each document to the console.

Listing 8-18. Iterating over the Documents Collection Using foreach

foreach (Word.Document doc in Application.Documents) { Console.WriteLine(doc.Name); }

 

Accessing a Document in the Documents Collection

To access a Document in the Documents collection, you use the get_Item method, which returns a Document object. The get_Item method has an Index parameter passed by reference that is of type object. You can pass an int representing the 1-based index of the document in the collection you want to access.

Alternatively, you can pass a string representing the name of the document you want to access. The name you pass for a document is the full name of the file if it has been saved (for example, "c:Documents and SettingsJohnDesktop Doc1.doc"). If the document has not yet been saved, the name to pass is the temporary name that Word creates for a new document. This temporary name is typically something like Document1, with no file extension. Listing 8-19 shows an example of calling get_Item with a 1-based index and a string index.

Listing 8-19. A VSTO Customization That Uses get_Item to Get a Document

private void ThisDocument_Startup(object sender, EventArgs e) { // Add 5 documents for (int i = 0; i < 5; i++) { Application.Documents.Add(ref missing, ref missing, ref missing, ref missing); } // Iterate over the open documents using foreach foreach (Word.Document doc in Application.Documents) { MessageBox.Show(doc.Name); } // Get a document by 1-based index. object index = 2; Word.Document doc1 = Application.Documents.get_Item(ref index); MessageBox.Show(String.Format( "The document at index {0} is {1}.", index, doc1.FullName)); // Get a document by full name object stringIndex = doc1.FullName; Word.Document doc2 = Application.Documents.get_Item(ref index); MessageBox.Show(String.Format( "The document at string index {0} is {1}.", stringIndex, doc2.FullName)); }

You can also use the Count property to determine the number of open documents. You should check the Count property before accessing a document by index.

Creating a New Document

To create a new document, you can use the Documents collection's Add method. The Add method returns the newly created Document object. It takes four optional by reference parameters of type object, as described in Table 8-5.

Table 8-5. Optional Parameters for the Documents Collection's Add Method

Parameter Name

What It Does

Template

Pass the short name of the template to be used (for example, "mytemplate.dot") if the template is in the Templates collection. If the template is not in the Templates collection, pass the full filename to the template (for example, "c:mytemplates template1.dot"). If you omit this parameter, Word uses the Normal template.

NewTemplate

Pass the bool value true if the document should be opened as a template. The default is false.

DocumentType

Pass a member of the WdNewDocumentType enumeration: wdNewBlankDocument, wdNewEmailMessage, wdNewFrameset, or wdNewWebPage. The default is wdNewBlankDocument.

Visible

Pass the bool value true if the document should be opened in a visible window. The default is TRue.

 

Opening an Existing Document

To open an existing document, use the Documents collection's Open method, which returns the opened Document object. The Open method takes one required object parameter to which you pass the string representing the filename to open. The Open method also takes 15 optional by reference parameters of type object, as described in Table 8-6.

Table 8-6. Optional Parameters for the Documents Collection's Open Method

Parameter Name

What It Does

ConfirmConversions

Pass true to display the Convert File dialog box if the filename passed to Open is not in Microsoft Word format.

ReadOnly

Pass true to open the document as read-only. If the document is already set to read-only on disk, passing false will not affect the read-only status of the document. The default is false.

AddToRecentFiles

Pass TRue to add the file name to the list of recently used files in the File menu. The default is true.

PasswordDocument

Pass a string representing the password for opening the document if the document is password protected.

PasswordTemplate

Pass a string representing the password for opening the template if the template is password protected.

Revert

If the document you are opening with the Open method is already opened in Word, pass TRue to discard any unsaved changes in the already open document. Pass false to activate the already open document.

WritePasswordDocument

Pass a string representing the password for saving changes to the document if the document is password protected.

WritePasswordTemplate

Pass a string representing the password for saving changes to the template if the template is password protected.

Format

Pass a member of the WdOpenFormat enumeration specifying the file conversion to be used when opening the document.

Encoding

Pass a member of the Office.MsoEncoding enumeration specifying the code page or character set to be used when you open the document.

Visible

Pass true to open the document in a visible window. The default is true.

OpenConflictDocument

Pass true to open the conflict file for a document that has offline conflicts.

OpenAndRepair

Pass true to try to repair a corrupted document.

DocumentDirection

Pass a member of the WdDocumentDirection enumeration specifying the horizontal flow of text in the opened document.

NoEncodingDialog

Pass true to prevent Word from displaying the Encoding dialog box if the text encoding of the document cannot be determined.

Listing 8-20 shows the simplest possible way to call the Open method to open a document. The code omits all the parameters by passing by reference the missing class member variable in VSTO, which is of type object and has been set to System.Type.Missing.

Listing 8-20. A VSTO Customization That Uses the Open Method to Open a Document

private void ThisDocument_Startup(object sender, EventArgs e) { object fileName = "c: est.doc"; Word.Document doc = Application.Documents.Open(ref fileName, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing); MessageBox.Show(String.Format( "Just opened {0}.", doc.Name)); }

 

Closing All Open Documents

The Close method on the Documents collection closes all the open documents in Word. It takes three optional parameters of type object by reference. The first optional parameter, called SaveChanges, is of type object and can be passed a member of the WdSaveOptions enumerationeither wdDoNotSaveChanges, wdPromptToSaveChanges, or wdSaveChanges. The second optional parameter, called OriginalFormat, is of type object and can be passed a member of the Wd-OriginalFormat enumeration. The second parameter controls Word's behavior when saving a changed document whose original format was not Word document format. This parameter can be passed wdOriginalDocumentFormat, wdPromptUser, or wdWordDocument. The final optional parameter is called RouteDocument and is of type object. Passing true for this parameter routes the document to the next recipient if a routing slip is attached.

It is also possible to close an individual document using the Document object's Close method, as discussed later in this chapter. You have already learned how to use the Application object's Quit method as a third way to close all open documents and quit Word. The Quit method takes the same parameters as Documents.Close and Document.Close.

Saving All Open Documents

The Save method on the Documents collection saves all the open documents in Word. It takes two optional parameters. The first optional parameter, called NoPrompt, is of type object and can be set to TRue to have Word automatically save all open documents without prompting the user. The second optional parameter, called OriginalFormat, is of type object and can be passed a member of the WdOriginalFormat enumeration. The second parameter controls Word's behavior when saving a changed document whose original format was not Word document format.

It is also possible to save an individual document using the Document object's Save or SaveAs methods, as discussed later in this chapter.

Категории