C # Operations Word (2)--open & Close Word document

Source: Internet
Author: User

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
    1. 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
  1. Private Msword.application M_word;
  2. Private Msword.document M_doc;
  3. Public Form1 ()
  4. {
  5. InitializeComponent ();
  6. }
  7. private void OnLoad (object sender, EventArgs e)
  8. {
  9. M_word = new Msword.application ();
  10. }

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
  1. Private void OnOpen (object sender, EventArgs e)
  2. {
  3. Object filename = "Test.docx";
  4. Object filefullname = @"C:\Users\David_ss\Desktop\ project Management \test.docx";
  5. Object confirmconversions = Type.Missing;
  6. Object readOnly = Type.Missing;
  7. Object addtorecentfiles = Type.Missing;
  8. Object passworddocument = Type.Missing;
  9. Object passwordtemplate = Type.Missing;
  10. Object revert = Type.Missing;
  11. Object writepassworddocument = Type.Missing;
  12. Object writepasswordtemplate = Type.Missing;
  13. Object format = Type.Missing;
  14. Object encoding = Type.Missing;
  15. Object visible = Type.Missing;
  16. Object openconflictdocument = Type.Missing;
  17. Object Openandrepair = Type.Missing;
  18. Object documentdirection = Type.Missing;
  19. Object noencodingdialog = Type.Missing;
  20. For (int i = 1; I <= M_word. Documents.count; i++)
  21. {
  22. String str = M_word. Documents[i]. Fullname.tostring ();
  23. if (str = = Filefullname. ToString ())
  24. {
  25. MessageBox.Show ("Do not open this document repeatedly");
  26. return;
  27. }
  28. }
  29. Try
  30. {
  31. M_word. Documents.Open (ref filefullname,
  32. ref confirmconversions, ref readOnly, ref addtorecentfiles,
  33. ref passworddocument, ref passwordtemplate, ref revert,
  34. ref writepassworddocument, ref writepasswordtemplate,
  35. ref format, ref encoding, ref visible, ref openconflictdocument,
  36. ref openandrepair, ref documentdirection, ref noencodingdialog
  37. );
  38. M_word.  Visible = true;
  39. //messagebox.show (M_word.  Documents.Count.ToString ());
  40. //messagebox.show (M_word. DOCUMENTS[1].  Fullname.tostring ());
  41. }
  42. catch (System.Exception ex)
  43. {
  44. MessageBox.Show ("Error opening Word document");
  45. }
  46. }


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
    1. Private void Onshowinfo (object sender, EventArgs e)
    2. {
    3. System.Diagnostics.Debug.WriteLine ("Number of currently open documents:" +m_word.  Documents.Count.ToString () +"\ n");
    4. System.Diagnostics.Debug.WriteLine (M_word. ActiveDocument.Paragraphs.Count.ToString ());
    5. }


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
  1. Private void OnClose (object sender, EventArgs e)
  2. {
  3. //Avoid pop-up Normal.dotm used dialog box, auto Save template
  4. M_word.  normaltemplate.saved = true;
  5. //Close open documents First (note savechanges option)
  6. Object saveChanges = MSWord.WdSaveOptions.wdSaveChanges;
  7. Object OriginalFormat = Type.Missing;
  8. Object routedocument = Type.Missing;
  9. M_word.  Documents.close (ref saveChanges,ref originalformat, ref routedocument);
  10. //If no documents exist, close the application
  11. if (M_word. Documents.count = = 0)
  12. {
  13. M_word. Quit (Type.Missing, Type.Missing, Type.Missing);
  14. }
  15. }


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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.