Background
Automation is a process that allows applications written in programming languages such as Visual Basic. NET or C # to programmatically control other applications. Automation to Word allows you to perform operations such as creating a new document, adding text to the document, merging emails, and controlling the document format. Using Word and other Microsoft Office applications, almost all the operations you can perform manually on the user Panel can be achieved through automated programming. Word uses an object model to implement this programming function (programmatically functionality ). Object models are a series of classes and methods that provide services similar to the logical components of Word. For example, an application object, a document object, and a paragraph object contain the functionality of the corresponding component of Word.
Project
In. NET, you need to add a COM reference to your project by right-clicking references in the solution window and adding references. Click the COM tag to find the Microsoft Word 10.0 Object Library. Click "select" to add and click "OK" to return.
This will automatically place an assembly in your application folder to bond the COM interface to Word.
Now, you can generate an instance of the Word application.
Word. ApplicationClass oWordApp = new Word. ApplicationClass ();
You can call the interesting methods and properties provided by Microsoft Word to operate documents in Word format. The best way to learn how to manipulate Word, Excel and PowerPoint object models is to use a macro recorder in these Office applications:
1. Select "Recording new macro" in the "macro" option in the "Tools" menu, and then execute the tasks you are interested in.
2. Select "stop recording" in the "macro" option in the "Tools" menu ".
3. Once you have finished recording, select "macro" under the "macro" option in the "Tools" menu, select the macro you have recorded, and click "edit ".
This will bring you into the generated VBA code, which completes the tasks you recorded. Note that the macro recorded is not the best code in most cases, but it provides a fast and available example.
For example, to open an existing file and add some text:Copy codeThe Code is as follows: object fileName = "c: \ database \ test.doc ";
Object;
Object isVisible = true;
Object missing = System. Reflection. Missing. Value;
Word. ApplicationClass oWordApp = new Word. ApplicationClass ();
Word. Document oWordDoc = oWordApp. Documents. Open (ref fileName,
Ref missing, ref readOnly,
Ref missing,
Ref missing,
Ref missing, ref missing, ref isVisible,
Ref missing, ref missing, ref missing );
OWordDoc. Activate ();
OWordApp. Selection. TypeText ("This is the text ");
OWordApp. Selection. TypeParagraph ();
OWordDoc. Save ();
OWordApp. Application. Quit (ref missing, ref missing, ref missing );
Or open a new document and save it:Copy codeThe Code is as follows: Word. ApplicationClass oWordApp = new Word. ApplicationClass ();
Word. Document oWordDoc = oWordApp. Documents. Add (ref missing,
Ref missing, ref missing, ref missing );
OWordDoc. Activate ();
OWordApp. Selection. TypeText ("This is the text ");
OWordApp. Selection. TypeParagraph ();
OWordDoc. SaveAs ("c: \ myfile.doc ");
OWordApp. Application. Quit (ref missing, ref missing, ref missing );
In C #, the open method of the Word document class is defined as: Open (ref object, ref object, ref object ). This indicates that the C # Open Method accepts 15 required parameters. Each parameter must be prefixed with the ref keyword and each parameter must be of the Object type. Because the first parameter is a file name, usually a String value in Visual Basic. NET, we must declare an Object-type variable to save the string value of C #. The Code is as follows:
Object fileName = "c: \ database \ test.doc ";
Although we only need to use the first parameter in the Open method, remember that C # does not allow optional parameters. Therefore, we provide the remaining 14 parameters in the form of Object variables, they save System. reflection. missing. value.
Use Template
If you use automation to create documents in the same format, It is very convenient to use a predefined template to process new documents. Using templates in your Word automation client program has two significant advantages over using templates without templates:
· You can have more control over the format and Object Location of your document.
· You can use less code to create your documents
By using templates, you can adjust the positions of tables, paragraphs, and other objects in the document, as well as the format of these objects. By using automation, you can create a document based on your template, instead of using the following code:
Word. ApplicationClass oWordApp = new Word. ApplicationClass ();
Object oTemplate = "c :\\ MyTemplate. dot ";
OWordDoc = oWordApp. Documents. Add (ref oTemplate,
Ref Missing, ref Missing, ref Missing );
In your template, you can define bookmarks so that your automated Customer program can enter variable text at a specific position in the document, as shown below:
Object oBookMark = "MyBookmark ";
OWordDoc. Bookmarks. Item (ref oBookMark). Range. Text = "Some Text Here ";
Another advantage of using a template is that you can create the storage format style of the application during runtime, as shown below:
Object oStyleName = "MyStyle ";
OWordDoc. Bookmarks. Item (ref oBookMark). Range. set_Style (ref oStyleName );
Use the CCWordApp class
This project contains a file: CCWordAPP. cs. I don't want to write code every time to insert text, open a file, and so on ...... So I decided to write a CCWordApp class to include most important methods. The following is a brief description of this class and its methods.Copy codeThe Code is as follows: public class CCWordApp
{
// It's a reference to the COM object of Microsoft Word Application
Private Word. ApplicationClass oWordApplic;
// It's a reference to the document in use
Private Word. Document oWordDoc;
// Activate the interface with the COM object of Microsoft Word
Public CCWordApp ();
// Open an existing file or open a new file based on a template
Public void Open (string strFileName );
// Open a new document
Public void Open ();
// Deactivate the interface with the COM object of Microsoft Word
Public void Quit ();
// Save the document
Public void Save ();
// Save the document with a new name as HTML document
Public void SaveAs (string strFileName );
// Save the document in HTML format
Public void SaveAsHtml (string strFileName );
// Insert Text
Public void InsertText (string strText );
// Insert Line Break
Public void InsertLineBreak ();
// Insert multiple Line Break
Public void InsertLineBreak (int nline );
// Set the paragraph alignment
// Possible values of strType: "Centre", "Right", "Left", "Justify"
Public void SetAlignment (string strType );
// Set the font style
// Possible values of strType: "Bold", "Italic," Underlined"
Public void SetFont (string strType );
// Disable all the style
Public void SetFont ();
// Set the font name
Public void SetFontName (string strType );
// Set the font dimension
Public void SetFontSize (int nSize );
// Insert a page break
Public void InsertPagebreak ();
// Go to a predefined bookmark
Public void GotoBookMark (string strBookMarkName );
// Go to the end of document
Public void GoToTheEnd ();
// Go to the beginning of document
Public void GoToTheBeginning ();
In this way, the operation to open an existing file is:
CCWordApp test;
Test = new CCWordApp ();
Test. Open ("c: \ database \ test.doc ");
Test. InsertText ("This is the text ");
Test. InsertLineBreak;
Test. Save ();
Test. Quit ();
Details
Examples include:
CCWordApp. cs-the class
CreateDocModel. aspx: Create a template-based document and use bookmarks.
CreateNewDoc. aspx: create a document and insert some text examples.
ModifyDocument. aspx: open an existing document and add some text examples later.
Template \ template1.dot: An example of a template (used in CreateDocModel. aspx ).
Remember, the directory for saving files must be writable. View the Web. config file to modify the path.
Reference
Microsoft Word Objects
Converting Microsoft Office VBA Macros to Visual Basic. NET and C #
HOWTO: Automate Microsoft Word to Perform a Mail Merge from Visual Basic. NET
A Primer to the Office XP Primary Interop Assemblies
HOWTO: Find and Use Office Object Model Documentation
Creating and Opening Microsoft Word Documents from. NET using C #