Use. Net to access the Office Programming Interface

Source: Internet
Author: User

In this articleArticleIn this section, I will introduce how to access the open programming interfaces of office in. net. In fact, no matter which specific technology is used for office development (such as vsto, or use C # To write an office add-in, or in a winformsProgramTo call the office function, or even start an Excel process on the server of an ASP. NET application), as long as it is based on the. NET platform, the content described in this article is valuable.

 

In this and subsequent articles, all presentations will be based on Office 2003 Professional and Visual Studio 2005. Using Visual Studio 2005 does not mean that we cannot use these methods in Visual Studio 2003 to access the office programming interface. On the contrary, this article and almost all subsequent demonstrations, all can be completed in Visual Studio 2003. The reason why I use Visual Studio 2005 is that I like its better IDE features. :)

 

I. Office Pia

 

As mentioned in the first article, office programming interfaces are made public through the COM component. Any program that accesses the office programming interface must actually call the office COM component. If you are a programmer who has just been engaged in Windows platform development for a short time and is learning and using. net at the beginning, you may feel depressed again. Fortunately,. Net allows developers to conveniently access COM components. I will use concise and clear descriptions to help you understand how we access the Office COM component in. net.

 

(1) InterOP assembly

 

In the. NET Framework, a technology called com InterOP is provided, which is specifically used to enable usCodeTo directly access the COM component. Its basic principle is ,. NET framework can automatically generate an InterOP assembly (intercall assembly (IA) for a COM component. IA is a fully hosted assembly. The namespaces, classes, methods, and so on in Ia all correspond to the COM component. In our. Net program, we can directly reference this IA and call the related methods in it. At this time, IA will help us access the corresponding methods in the real COM component. The final result is that in our own applications, we only need to call a pure. Net IA.

 

The following figure shows how IA can help our program access the COM component.

 

The method for generating an IA is very simple. When we add a new COM component reference in the Visual Studio development environment, Visual Studio will automatically generate a corresponding IA for us. For example, we demonstrate referencing Microsoft XML 5.0 components in a project.

 

When you click the OK button in, Visual Studio automatically generates an IA for the Microsoft XML 5.0 component. Open the OBJ \ DEBUG directory of the project directory and you will see a file named InterOP. msxml2.dll Assembly file, which is automatically generated by IA, and Visual Studio automatically references this ia assembly in the project. For example.

 

(2) Primary InterOP assembly

 

In our own applications, the basic principle of the method for accessing the Office COM component is as described below, and the COM component in office is indirectly accessed through COM InterOP through IA. However, for the office software, there is a special difference, that is, we should not generate an "own" IA in Visual Studio to access office COM, however, you need to use the "official" Pia provided by Microsoft.

 

Pia can be understood as an official interoperability assembly. The main difference between Pia and IA is as follows:

1. IA is automatically generated by developers on the development machine through the wizard, and Pia is provided by the software vendor (for the Office software, Microsoft;

2. Pia has been optimized by the vendor to make it easier to be called by. net;

 

(3) Office primary InterOP assembly

 

Therefore, we should use PIA to access the Office COM component instead of IA. So how to install office Pia on our computer?

 

If your machine has been installed. net Framework, so when installing the Office, in the advanced custom options of the Installation Wizard, we are in the sub-options of each component (Word, Excel, powperpoint, etc, you can see a ". net programmable support ", choose to install it, The office2003 installation program will automatically install Pia on our computer.

 

In addition, Microsoft provides an installation package for the distribution of office Pia clients (that is to say, Pia is uniformly installed for all our software users. Can be in http://www.microsoft.com/downloads/details.aspx? Familyid = 3c9a983a-ac14-4125-8ba0-d36d67e0f4ad & displaylang = EN download to this distribution installation package.

 

Office Pia divides Office components (Word, Excel, PowerPoint, outlook, etc.) into multiple separate assemblies. For example, the PIA assembly corresponding to word is Microsoft. office. interOP. word. DLL (the classes in the program set are all placed in the namespace Microsoft. office. interOP. in word), the Excel assembly is Microsoft. office. interOP. excel. DLL (the classes in the program set are all placed in the namespace Microsoft. office. interOP. in Excel ). In addition, some components (such as the menu bar) shared by office are placed in a separate Assembly: office. dll (the corresponding namespace is Microsoft. Office. InterOP. Core ).

 

If office PIA has been installed on our development machine, when we reference the Office COM component in Visual Studio through the method described above, visual Studio detects that office PIA has been installed on the local machine, and then it directly references the installed Pia without generating a new Ia automatically.

 

For example, we add a reference to the word COM component in Visual Studio (word is "Microsoft Word 11.0 Object Library" in the COM component list, which is similar, the COM component names of Excel, outlook, and PowerPoint all follow this rule ).

 

After clicking the OK button, you can see in the project manager that Visual Studio has helped us reference the components to be referenced. In fact, in addition to the word component to be referenced, other additional but necessary components such as Microsoft. Office. Core, stdole, and vbide have been automatically referenced.

 

Right-click the word component reference and view its attributes. In its path attributes, we can see that the PIA file is actually in "C: \ windows \ Assembly \... "Directory, which is the directory where the Global Assembly Cache (GAC, Global Assembly Cache) is located. This is because office Pia is installed in the GAC on the machine, so the reference to office Pia will direct to the corresponding file in GAC.

 

2. go deep into office Pia

 

If you have used VBA for Development (or use other development tools such as VB, Vc, or Delphi to directly call the office ), in fact, you have a certain understanding of the office COM interface, because the code for operations such as application, document, and range written in the VBA editor, in fact, it is the application, document, and range classes in the office COM component.

 

We already know that the Office COM component has been encapsulated in office Pia, so we can foresee that for classes or interfaces in every office COM component, in the office Pia assembly, we should be able to find a corresponding class or interface. Next, we will use the Object Browser to open the office COM component directly, and then open office Pia, so that we can compare them to better understand them.

 

In Visual Studio, open the Object Browser in the View menu, and click Add other components in the Object Browser. In the displayed selection window, select "Microsoft Word 11 Object Library" in the COM component. Then, the Object Browser directly opens the COM component of Word 2003, as shown in.

 

In the word COM component member list shown in, you can see that I have selected the quit () method of the application class in word. The application class can be said to be the core class of each office component. No matter Word, Excel, or PowerPoint, there is a corresponding application class that corresponds to the main programs of Word, Excel, and PowerPoint. If you want to open Word directly in our program, you need to create an instance of this application class. If you want to close this newly opened Word program, call the quit () method of the newly created application object.

 

Next, we use the Object Browser to open the assembly corresponding to word in office Pia. In the previous steps, we have referenced the PIA of word in the project. In the reference list of the Project Manager, select word, right-click, and select view in the Object Browser, you can open the PIA of word in the Object Browser. For example.

 

If you browse the classes in the Microsoft. Office. InterOP. Word namespace shown in, you will find a very interesting thing. That is, the classes and interfaces in Pia of word are not exactly the same as those in COM of word. For example, we can see a class called application in the word COM component, but in Pia of word, we can only find an interface called application and a class called applicationclass.

 

The reason for this is. net com InterOP (specifically. net sdk's tlbimp.exe command line tool) helps us generate InterOP Assembly Based on COM components, in fact, it will not be generated against COM components one by one.. Net class and interface. Instead, it generates the corresponding. Net class and interface according to certain rules.

 

Because application is the most important part of the word programming interface, briefly describe its conversion rules (the actual interfaces and analogy described below are more and the related relationships are more complex ). First, A _ application interface is generated in Word Pia. This _ application interface basically describes all the operations and properties in the application class of the word COM component. Then, multiple applicationevents_event series interfaces (applicationevents2_event, applicationevents3_event, applicationevents4_event, and applicationevents4_event) are generated in Word Pia... We don't need to worry about these details). This interface basically describes all the events in the application class of the word COM component. Then, an applicatin interface is generated in Word Pia, which implements the _ application interface and applicationevents_even interface. In this way, the application interface basically describes all the operations, properties, and events in the application class of the word COM component. Finally, a specific applicationclass class is generated in Word Pia, which implements the applicatin interface.

 

If you have been overwhelmed by the above descriptions, remember: In word Pia, we have an application interface and an applicationclass class, the application interface describes all the members of the application class in the corresponding word COM component, and the applicationclass class is a specific implementation class.

 

Iii. Code Walkthrough: A. Net winforms Program

 

Finally, after you have endured N for a long time and barely finished reading those long-winded texts, you can see a specific demonstration. We need to use C # To write a Windows application. In this program, we start word, operate it with code, and then close it.

 

First, create a new C # windows application, and then use the method described above to reference the PIA of word in the project (in the Add reference interface, select Microsoft Word 11 Object Library in the COM component list ).

 

Put two button controls on the automatically created startup form, one is btnstartword and the other is btnstopword. We hope that when you click btnstartword, our program will automatically start word, create a new word document, and save it to the disk. When you click btnstopword, close the word. The Form Design view is as follows.

 

 

In this main form classSource codeWe reference the namespace of word Pia. We use MSWord to replace the complete namespace name Microsoft. Office. InterOP. word:

 

Using MSWord = Microsoft. Office. InterOP. word;

 

In the source code of the main form class, add a class-level member. _ wordapp is an application-type object (remember: MSWord. application is an interface !) :

 

Private MSWord. Application _ wordapp = NULL;

 

Then, add the following code in the Click Event code of the btnstartword button. The Code creates a new word instance and displays it:

 

_ Wordapp = new MSWord. Application ();

_ Wordapp. Visible = true;

 

Here, many people have a very big doubt, that is, MSWord. application is actually an interface, how can we use "New MSWord. application () "to create a word instance? Shouldn't we use "New MSWord. applicationclass? After all, applicationclass is the specific class that implements the application interface.

 

Here, office Pia provides us with a small "cookie". We can actually use "New MSWord. application () "to create a word program instance, we only need to know that office Pia will automatically create a real word program instance for us.

 

Next, we will add the following code to the Event code of the btnstartword button.

 

Object missing = type. missing;

Object sfilename = "C: \ sample.doc ";

 

MSWord. Documents docs = _ wordapp. documents;

MSWord. Document Doc = docs. Add (ref missing, ref missing );

Doc. saveas (ref sfilename, ref missing, ref missing, ref missing, ref missing );

Doc. Close (ref missing, ref missing, ref missing );

 

In the above code, we can access the documents attribute of the application to obtain a documents class, and then create a new document using the add () method of the documents class, obtain the object of the document type corresponding to this new document, save the document on disk using the saveas () method of the document class, and finally close () of the document class () method to close this new document.

 

Well, I know that I have not explained it thoroughly enough. What do the ref, missing, and so on in the code above mean? Why should I use them, I believe many people are very confused (especially programmers who have used VBA or other languages to access the Office COM Component Interface ). This actually involves a "syntax compatibility" problem of calling the office programming interface in C # language. That is to say, the Office product development team is actually specially designed to be called by VBA when designing the programming interface. Therefore, the interfaces are very compatible with the VBA syntax, making VBA programmers feel as convenient as possible. However, the C # syntax is different from the VB syntax, so when using C # To access the office programming interface, you will feel awkward ".

 

Here, I just want to explain the code below:

(1) Many office programming interfaces contain many parameters (for example, the document. saveas () method has 16 parameters !!!), In fact, when we call them, not every parameter needs to specify a specific value (such as document. for the saveas () method, you only need to specify the first parameter, that is, where the parameter is saved). For parameters that do not need to specify a specific value, we can directly pass a parameter. net class library comes with the static object: type. missing is enough.

(2) parameters of many office programming interfaces must be referenced but cannot be passed. Therefore, when calling these methods, for parameters, you must add the ref keyword in C. For example, the document. add (), document. saveas (), document. close () method. All their parameters must be referenced. Therefore, the ref keyword is added before each parameter.

 

For a more comprehensive description of the "syntax compatibility" problem when calling the office programming interface in C # language, see Office. net (2)-C # syntax compatibility when accessing the office programming interface.

 

Continue to add code for our project. In the event code of the btnstopword button, fill in the following code:

 

Object missing = type. missing;

 

_ Wordapp. Quit (ref missing, ref missing, ref missing );

 

_ Wordapp = NULL;

 

GC. Collect ();

GC. waitforpendingfinalizers ();

GC. Collect ();

GC. waitforpendingfinalizers ();

 

The above code exits the word program by calling the application. Quit () method. The more important part is how to release the word program instance. The above Code uses a simple but effective method to disable and recycle the word program process. First, the object _ wordapp is assigned a null value, in this way, the word application object will not be referenced by any variable, and will be forcibly called.. NET Framework, so that the application object can be recycled by the garbage collector. (Actually ,. the garbage collector of Net Framework only recycles a packaging object of office Pia, but after this packaging object is recycled, the COM component object corresponding to the word program will find that it is no longer referenced by any other object, and the reference count is changed to 0, so the COM component will be actually released .)

 

How to disable the Office program in your own applications is not a small problem. The method described above is not 100% effective, for a more complete description of this topic, see Office. net (2)-close the office program completely clean.

 

Our first demo program has been written here. Now we can run this program and click the first button to start word, operate word to create a new document and save it to the disk. Then click the second button to close word.

 

(Iv) Summary

 

This document briefly describes how to access the office programming interface in. NET and explains the concept and usage of office Pia. From this article, we can see that operating on the office in. NET is very simple and straightforward. Microsoft has greatly simplified the work of. Net programmers by providing office Pia.

 

Reprinted from: http://hi.baidu.com/sammyhxm/item/fd16be28dcdd6fc0ee10f1a6

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.