Using Microsoft Visual C # for Microsoft Word 2002 and Excel 2002 programming (i)

Source: Internet
Author: User
Tags command line documentation net command object model object object prepare microsoft c visual studio
Excel|visual|word| Programming Microsoft Word 2002 and Excel 2002 programming using Microsoft Visual C #
Kerry Loynd and Siew-moi Khor
Microsoft Corporation
October 2002
Apply to:
Microsoft®office XP
Microsoft Visual c#™
Summary: Learn about COM interoperability between Microsoft C # and large, complex COM servers. This article describes how to prepare Office XP COM objects and how to use them in a C # program, and also provides tips to help you understand why certain actions must be implemented in a specific way.
Download or browse the Odc_offcs.exe in MSDN Downloads (English).


Directory


    • Brief introduction
    • System Requirements
    • Some quick start knowledge for. NET
    • Using Office XP Primary Interop assemblies
    • Code Walkthrough
      • Example 1: Start Word Application Object
      • Example 2: Create a new Word document
      • Example 3: Open an existing Word document
      • Example 4: Events that are exposed using Word
      • Example 5: Animate the Office Assistant
      • Example 6: Default Properties and Indexed properties
    • Summary
Brief Introduction
One of the most powerful features of Microsoft®office XP is that its components, such as Microsoft Excel 2002 and Microsoft Word 2002, expose their functionality in the form of Component Object Model (COM) interfaces. It is relatively easy to access these COM interfaces through Microsoft Visual basic®6.0, but it can be difficult to use these interfaces and public classes through C or C + +. However, Microsoft. NET and Microsoft c#™ or Microsoft Visual c++®, which have managed extensions, can easily use COM objects exposed by Office XP, like Visual Basic 6.0.
This article assumes that you want to do Office XP programming. Although a hyperlink to a MSDN® document is provided throughout this article, you should be familiar with or have access to the Office XP programming documentation for the content described in this article.
This document describes the interfaces and common classes that Office XP provides and how they are used. The content of the document is expressed in Visual Basic programming language, so you need to convert the method and event signatures in your mind. This article describes how to do this transformation, how to prepare COM objects for Office XP, and how to use these COM objects in a C # program. Finally, this article provides tips to help you understand why certain actions must be implemented in a specific way. With this information, you should be able to take advantage of other COM servers that use C #. System Requirements
To run the sample, the following software needs to be installed on the computer:
    • Microsoft Windows®xp or Microsoft Windows 2000 and related Service packs (SPS)
    • Microsoft Office XP and the associated SP
    • Microsoft. NET Framework (English) and associated SP
    • Microsoft Office XP Primary Interop Assemblies (PIA) (English)
    • Microsoft Visual studio®.net
Some quick start knowledge for. NET
The. NET technology introduces the concept of an assembly as a basic executable unit. An assembly can be an executable (. exe) or dynamic-link library (. dll) and can contain multiple files. The assembly contains all the information about the code, type, and resources needed to run the program.
To use COM objects exposed by Office XP, you need to use the primary interop assembly (PIA) so that the C # compiler can find the interfaces and public classes that Office XP exposes.
This article will not elaborate on the content of interop assemblies or PIAs. For more information about PIAs, see Primary Interop Assemblies (PIA). The download address for the Office XP PIA is provided in this article using the Office XP Primary interop Assembly section.
Knowing the type information that is exposed will usually give you some insight. Microsoft Visual Studio®.net provides a tool called ILDASM that lists type information encapsulated in an assembly. Figure 1 is a partial screenshot of the ILDASM display of Word 2002 primary interop assembly information.
Note: to open the ILDASM tool, click Start, point to Programs, point to Microsoft Visual Studio. NET, and then point to Visual Studio. NET Tools(Vi Sual the studio. NET tool) and click Visual Studio.NET command Prompt (Visual Studio. NET commands prompt). In the Visual Studio. NET command Prompt(Visual Studio. NET commands) window, type ildasm. The ILDASM window opens later. To view type information for a particular interop assembly or PIA, on the File menu , click Open. Browse to the location of the interop assembly or PIA, select the interop assembly or PIA you want to view, and click Open.


Figure 1: Using the ILDASM tool to view type information for an interop assembly
Such as Figure 1As shown, the assembly is in Microsoft.Office.Interop.Word.dll, and the interfaces and public classes are encapsulated in the Microsoft.Office.Interop.Word namespace. ApplicationThe public class has been expanded to see that it expands (in terms of C + + and C #, derived) Application, and in Word implements the applicationevents2_eventInterface. All of these will be discussed in detail in the following sections of this article. using Office XP Primary Interop Assemblies
Before you run the examples included in this article, you should install Microsoft Office XP Primary Interop Assemblies (PIAs) on your computer. After you install the PIA, you must place it in a location that the compiler and the completed program can access. For more information, see the Readme file contained in the Office XP PIA download Document and the. NET Framework Developer ' s Guide (to read it, click Start, point to Programs, and then point to Microsoft. NET Framework SDKand click Documentation[Document]) in the article "Assembly Location".
For demonstration purposes, this article unzip the Office XP PIA to the following folder: C:\Office XP pias\. It is then installed into the global assembly cache (GAC) and registered (for more information about this operation, see the Readme file for Microsoft Office XP Primary Interop Assemblies (PIA) [English]).
You can call this compiler by typing the C # compiler's executable name  at the command line. After you install and register the PIAs, you can use the/r option, as in any other assembly Reference to it on the command line. If the location of the PIA is inaccessible, the program fails at run time and generates a System.IO.FileNotFoundExceptionOr System.TypeInitializationExceptionType of exception that tells which assembly cannot load.
Next, in the "How to compile and run Example1.cs" section, you will learn how to use the command line to build a C # program and reference a PIA.
The examples included in this article use three Office XP PIAs:
    • Microsoft.Office.Interop.Word.dll
    • Office.dll
    • Microsoft.Office.Interop.Excel.dll
Code Walkthrough
Before you demonstrate the code example, you should first download the Odc_offcs.exe file and extract the sample program into C:\CSOfficeSamples or the directory of your choice. For ease of reference, in all of the following examples, the example program is assumed to be in the C:\CSOfficeSamples directory.
The download document contains five Word 2002 sample programs (Example1.cs, Example2.cs, Example3.cs, Example4.cs, and Example5.cs) and an Excel 2002 sample program (Excel1.cs). The sample source file's corresponding sample generation file (Example1.exe, Example2.exe, etc.) is also included in it for readers to use.
All code examples are commented on in detail.


Example 1: Start Word Application Object



The first example is very simple, showing only how to start Word 2002 and leave it open for a few seconds before closing it. First take a look at the main lines of code in the Example1.cs source file. The following code fragment assigns Applicationobject and its base class object, but is actually doing CoCreateInstanceCall.
Application app = new application ();

Applicationof the class QuitMethod accepts three parameters: SaveChanges, OriginalFormat, and Routedocument. These optional parameters can be omitted in Visual Basic code, and there are no optional parameters in C #; All three parameters must be passed to the Quit。 In C # You can assign a value missing.value to each optional variable (used to notify QuitMethod uses the default behavior) to achieve the same effect. In this example, it means "do not save the document, preserve the initial formatting of the document, and do not route selection."
Object saveChanges = Missing.value;object OriginalFormat = Missing.value;object routedocument = Missing.value;app. Quit (ref saveChanges, ref originalformat, ref routedocument);

Note that all three parameters are marked with the REF keyword. Because these methods were originally written in Visual Basic, Visual Basic passes the parameters by reference by default. Therefore, you must also pass parameters here by reference.


How to build and run Example1.cs



To run the example, you first build the Examle1.cs sample. To be in Visual Studio. NET Command PromptThe example is generated in the Visual Studio. NET Command Prompt window:
    1. Go to the C:\CSOfficeSamples directory or save any directories for the example. As shown in Figure 2 , type the CD C:\CSOfficeSamples after the command prompt.
    2. Then, after the command prompt shown in Figure 2 , type /r: "C:\Office XP pias\microsoft.office.interop.word.dll" Example1.cs Build Example1.cs.
      (If the Office XP PIA is saved in a different location, you will need to replace the following drive and installation paths with the corresponding values:/r: Drive:\< Installation path >\microsoft.office.interop.word.dll Example1.cs.
      Note: the command line compiles the example1.c s source file and generates the Example1.exe executable file. In this example, the executable file that you create is automatically saved in the same folder as the Example1.cs.
      Command line option/ R will refer to Microsoft.Office.Interop.Word.dll. If an error occurs in the path of the Microsoft.Office.Interop.Word.dll Pia (or any of the referenced PIAs), the program fails at run time and generates a System.IO.FileNotFoundException or system.typeinitializationexception type of exception that tells which component cannot load.


      Figure 2: Using the command line to generate the source file
    3. To run Example1.exe (located in the same folder as the Example1.cs source file), double-click the program.

The example is a very simple program that doesn't have any interesting features, so let's take a look at Example 2.


Example 2: Create a new Word document



Example2.cs, like Example 1, is also used ApplicationObject to start Word 2002, and then open the collection of documents that are encapsulated in the application.documentsproperty) to add a new document. The first meaningful piece of code appears when you create a new document:
Object Template=missing.value;object newtemplate=missing.value;object documenttype=missing.value;object visible=    True _document doc = App.                       Documents.Add (ref template, ref newtemplate, ref DocumentType, Ref visible);

ADDAll parameters of a method are optional, so you must specify a meaningful value for these parameters or specify a missing.value. In this example, the first three parameters (template, NewTemplate, and DocumentType) are set to Missing.Value because we do not need to use or create a template, and this is just a plain text document. Because you want this document to be visible in this example, set the parameter visible to true.
You might be able to determine whether the BooleanThe value assigned to the visible object was puzzled. That's why it's important to access Word 2002 programming documents. If you look at the Word 2002 object Model document for Documents.AddDescription of the method, you will see the following:
VisibleOptional Variant。 Set to TrueThe document opens in the visible window. If the value is False, Microsoft Word opens the document, but the document window's Visibleproperty is set to False。 The default value is True
Note: to see the Documents.Add method in Word 2002 Visual Basic documents, in the Tools menu of Word 2002, select Macros, and then click Visual Basic Editor. When you are in the keyboard state of the Visual Basic editor, press the F2 key to activate the Object Browser or press F1 to view Help. Then search for "Documents" or "Documents.Add". Similar documents can also be found on MSDN.

This begs the question: why does PIA expect ADDThe parameter type of the method is object, and the Documents.AddMethod Document shows Type Variant? This is because VariantThe type is marshaled automatically to the. NET Object object type, which is mapped to C # 's ObjectType. In this example, the parameter visible BooleanValue trueEncapsulated as object and passed to the Documents.Add () function.
The next line of important code is:
Doc. Words.First.InsertBefore

Use from App. The Documents.Add () function calls the returned document interface and adds some text at the beginning of the document. There is nothing special about this place.
Let's take a look at a more interesting piece of code, which is to save the document:
Object filename = environment.currentdirectory+ "\\example2_new"; #if officexpdoc.saveas2000 (ref filename, #elsedoc. SaveAs (ref fileName, #endif ref optional, ref optional, ref optional, ref optional, ref opt ional, ref optional, ref optional, ref optional, ref optional, ref optional);

The first thing to note is that the string that holds the file name is encapsulated in the FileName object. Second, this code will call the OfficeXP when it is defined. SaveAs2000method is called without defining the officexp. SaveAsMethod. As you may have guessed, SaveAsThe method signature differs between Office 2000 and Office XP.


How to build and run Example2.cs



To generate a xample2.cs, you can Visual Studio. NET Command PromptIn the Visual Studio. NET Command Prompt window, do the following:
    1. In the C:\CSOfficeSamples directory or in any directory that holds Example2.cs, type /r after the command prompt as shown in Figure 3 : "C:\Office XP pias\ Microsoft.Office.Interop.Word.dll "/d:officexp Example2.cs.
      (If the Office XP PIA is saved in a different location, you will need to replace the following drive and installation paths with the corresponding values: /r: Drive:\< Installation path >\microsoft.office.interop.word.dll/d:o Fficexp Example2.cs. )

      Figure 3: Compiling example2.cs using the command line (click picture to view large image)
    2. To run Example2.exe (located in the same folder as the Example2.cs source file), double-click the program.


Example 3: Open an existing Word document




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.