OK, and then the previous "Word object Model", this article formally began using the C # language to manipulate Word2007 in VS2010.
If you are not a friend of the Word object model, refer to the previous article, or download: C # operation Word2007.pdf.
----------------------------------Gorgeous split--------------------------------------------
1. Add Reference, add namespaces
After you create a new WinForm project, you need to add reference to the project first
Since my word is 2007, I chose Microsoft Word 12.0 Object Library,
Once added, the following two entries should appear in the reference form:
Microsoft.Office.Core
Microsoft.Office.InterOP.Word
--------------------------------------------------------------------------
The following is the official start of writing C # code dug.
First, add the Word namespace to your Form1.cs: I added:
[CSharp]View Plaincopy
- Using MSWord = Microsoft.Office.Interop.Word;
2. Open the Word document
Then add a message response function for the Load event to the form onload:
All right. Next, we refine the onload function:
[CSharp]View Plaincopy
- Private Msword.application M_word;
- Private Msword.document M_doc;
- Public Form1 ()
- {
- InitializeComponent ();
- }
- private void OnLoad (object sender, EventArgs e)
- {
- M_word = new Msword.application ();
- }
In onload we instantiate a word's Application object that represents the Word2007 application.
This opens only an empty shell of an application that has no documentation. Let's open an existing document.
Before opening, we add a button and then set the Click event Listener for it OnOpen ()
[CSharp]View Plaincopy
- Private void OnOpen (object sender, EventArgs e)
- {
- Object filename = "Test.docx";
- Object filefullname = @"C:\Users\David_ss\Desktop\ project Management \test.docx";
- 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;
- For (int i = 1; I <= M_word. Documents.count; i++)
- {
- String str = M_word. Documents[i]. Fullname.tostring ();
- if (str = = Filefullname. ToString ())
- {
- MessageBox.Show ("Do not open this document repeatedly");
- return;
- }
- }
- Try
- {
- M_word. Documents.Open (ref filefullname,
- 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
- );
- M_word. Visible = true;
- //messagebox.show (M_word. Documents.Count.ToString ());
- //messagebox.show (M_word. DOCUMENTS[1]. Fullname.tostring ());
- }
- catch (System.Exception ex)
- {
- MessageBox.Show ("Error opening Word document");
- }
- }
As you can see, the open method of the Documents object is called here, the parameters are many, and interested friends can refer to MSDN.
I wrote the file path directly in the code above, but the better way is to pop up the dialog box and select the file.
The code also checks to see if the document is open, which avoids repeating opening the same document two times. It is also important to note that the number of open documents in the Word application is from 1 (that is, 1 based), not the usual starting from 0, which needs to be noted:
for (int i=1; I<m_word. documents.count;i++)
After the Open method call is complete, do not forget to set the Visiable property of the Application object to True, otherwise you will not see the open document.
OK, you can compile and run. Such as:
3. View Word Document Information
Below, let's take a look at the information about the document, corresponding to the Document Information button (Listener Onshowinfo):
[CSharp]View Plaincopy
- Private void Onshowinfo (object sender, EventArgs e)
- {
- System.Diagnostics.Debug.WriteLine ("Number of currently open documents:" +m_word. Documents.Count.ToString () +"\ n");
- System.Diagnostics.Debug.WriteLine (M_word. ActiveDocument.Paragraphs.Count.ToString ());
- }
Because there are too many object properties in Word, you can choose two of them here. The first line is the number of currently open documents, and the second line is the number of natural segments of the currently active document:
You can see the output 1 and 2 respectively, right.
4. Close the Word document and exit the Word application
Finally, let's take a look at how to close it again, add the button first, and then add the OnClose () listener.
[CSharp]View Plaincopy
- Private void OnClose (object sender, EventArgs e)
- {
- //Avoid pop-up Normal.dotm used dialog box, auto Save template
- M_word. normaltemplate.saved = true;
- //Close open documents First (note savechanges option)
- Object saveChanges = MSWord.WdSaveOptions.wdSaveChanges;
- Object OriginalFormat = Type.Missing;
- Object routedocument = Type.Missing;
- M_word. Documents.close (ref saveChanges,ref originalformat, ref routedocument);
- //If no documents exist, close the application
- if (M_word. Documents.count = = 0)
- {
- M_word. Quit (Type.Missing, Type.Missing, Type.Missing);
- }
- }
It is important to note that in order to prevent pop-up Normal.dotm used dialog box, it is best to automatically save the template.
Then set up the saveoption you need. There are three kinds, namely
- wdSaveChanges
- wdDoNotSaveChanges
- wdPromptToSaveChanges
OK, let's introduce so much today. Let's introduce the Selection object and the Range object next time. -------------------------------Gorgeous split--------------------------------------Note: MSDN------>word.application Objects
MSDN------>word.document Objects
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
C # Operations Word (2)--open & Close Word document