Using C # for Word 2002 and Excel 2002 programming

Source: Internet
Author: User
Tags bool command line contains net command object model object object microsoft c visual studio
Excel|word| Programming 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.


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 (r) 6.0, but it is more difficult to use these interfaces and public classes through C or C + +. However, Microsoft. NET and Microsoft C #, which have Managed Extensions? or Microsoft Visual C + + (r) can easily use the COM objects exposed by Office XP, just like Visual Basic 6.0.



This article assumes that you want to do Office XP programming. Although hyperlinks to MSDN (r) documents are available 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 (r) 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 (r). 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.



Knowing the type information that is exposed will usually give you some insight. Microsoft Visual Studio (R). 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 (Visual Studio. NET tool) and click V isual 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



As shown in Figure 1 , the assembly is in Microsoft.Office.Interop.Word.dll, and the interfaces and common classes are encapsulated in the Microsoft.Office.Interop.Word namespace. The application public class has been expanded to see that it expands (derived from C + + and C # terms) applicationand implements APPLICATIONEVENTS2 in Word _event interface. 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 the "Assembly Location" article in the Framework SDK and click documentation [documentation].



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.



You can call this compiler by typing the C # compiler's executable name at the command line. After the PIAs are installed and registered, you can use the/r option to reference them on the command line as you would any other assembly. If the location of the PIA is inaccessible, the program fails at run time and generates a System.IO.FileNotFoundException or system.typeinitializationexception type 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 the application object and its base class object, but is actually making a CoCreateInstance call.



Application app = new application ();

  The Quit method of the application class accepts three parameters:saveChanges、originalFormatandrouteDocument. 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 Quitat call time. You can get the same effect in C # byMissing.Valueassigning values to each optional variable that notifies the Quit method of using the default behavior. 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 build this example in the Visual Studio. NET command Prompt(Visual Studio. NET commands) 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. Figure 2 , type/r after the command prompt: "C:\Office XP Pias\microsoft.office.interop.word.dll" Example1.cs generates 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: command line  to example1.c s source files To compile and generate 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. The
    command line options /R references Microsoft.Office.Interop.Word.dll. If an error occurs in the location 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 the type of exception to tell which component cannot be loaded.

    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, starts Word 2002 with the application object, and then opens the collection of documents that are encapsulated in the application.documents property) 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);





  All parameters of the Add method are optional, so you must specify a meaningful value for these parameters or specify a missing.value. In this example, since we don't need to use or create a template, and this is just a plain text document, set the first three arguments (template,newTemplateanddocumentType) toMissing.Value. Because you want this document to be visible in this example, set the parameter visible to true.



You may be puzzled about how to determine whether a Boolean value should be assigned to anvisibleobject. That's why it's important to access Word 2002 programming documents. If you look at the description of the Documents.Add method in the Word 2002 object Model document, you will see the following:



  Visible An optional Variant. Set to True to open the document in the visible window. If this value is false, Microsoft Word opens the document, but sets the Visible property of the document window 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 the PIA expect the Add method's argument type to be object, whereas the Documents.Add method document displays a Variantof the type? This is because the Variant type is marshaled automatically to the. NET Object object type, which is mapped to the type object of C #. In this example, the parameter visible encapsulates the Boolean value true to object and passes it to the Documents.Add()function.



The next line of important code is:



Doc. Words.First.InsertBefore



With theapp.Documents.Add() document interface returned from the function call, some text is added 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 officexp
Doc. SaveAs2000 (ref fileName,
#else
Doc. SaveAs (ref fileName,
#endif
Ref optional,
Ref optional,
Ref optional,
Ref optional,
Ref optional,
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 calls the SaveAs2000 method when the officexp is defined, and calls the SaveAs method without defining OfficeXP. As you may have guessed, there is a difference between Office 2000 and Office XP for theSaveAs method signature.



how to build and run Example2.cs



To build Xample2.cs, you can do the following in the Visual Studio. NET command Prompt(Visual Studio. NET commands) window:


    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:officexp Example2.cs. )

      Figure 3: Compiling example2.cs using the command line

    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



As with the Documents.saveas method, theDocuments.Open method signature differs between Office 2000 and OfficeXP, so the new name is wrapped in a #if Declaration. The Open method is as simple as the SaveAs method, as follows:





Object fileName = environment.currentdirectory+ "\\example3";
Object Optional=missing.value;
#if officexp
_document doc = App. documents.open2000 (ref fileName,
#else
_document doc = App. Documents.Open (ref fileName,
#endif
Ref optional,
Ref optional,
Ref optional,
Ref optional,
Ref optional,
Ref optional,
Ref optional,
Ref optional,
Ref optional,
Ref optional,
Ref optional);





The optional parameters are documented in the Help Word 2002 Visual Basic Reference and the instructions in the MSDN (English) about the Documents.Open method.



The more interesting code in this example is that the text in the open document is highlighted first and then cut:





Object first=0;
Object Last=doc. Characters.count;
Range r = Doc. Range (ref, ref, last);
R.select ();
Thread.Sleep (2000);
R.cut ();





The integer value of the first and last character positions is encapsulated into the first and last object and then passed to the Document.range () function, which returns the Range object called by the Select () function. This explicit encapsulation is required because the Range object expects to refer to its arguments, and any implicit or explicit conversion changes the argument to a right value and the right value cannot be passed by reference. This example causes the text to be highlighted for two seconds, and then the text is clipped. The cut operation can also be implemented through the following code:


Object first=0; Object units = Wdunits.wdcharacter; Object Last=doc. Characters.count; Doc. Range (ref, ref, last). Delete (ref units, ref last);

   how to build and run Example3.cs


To build Example3.cs, you can do the following in the Visual Studio. NET command Prompt(Visual Studio. NET commands) window:


    1. Open the directory where you saved the Example3.cs source file (for example, C:\CSOfficeSamples) and type /r after the command prompt : "C:\Office XP pias\ Microsoft.Office.Interop.Word.dll "/d:officexp Example3.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 Example3.cs. )
    2. To run Example3.exe (located in the same folder as the Example3.cs source file), double-click the program.


  Example 4: Events that are exposed using Word



This example involves more than a few other things, but it's not really complicated. The main reason for looking complex is that the name of an event and its handler type is longer. Take a look at the setup code for the documentopen and documentchange event handlers for the Office XP version:





... #if officexp applicationevents3_documentopeneventhandler myopendoc = new applicationevents3_ Documentopeneventhandler (Myopeneventhandler); ApplicationEvents3_DocumentChangeEventHandler myChangeDoc = new applicationevents3_ Documentchangeeventhandler (Docchange); #else ...





These two statements are just the event handlers that declare the event. In the next few lines of code, these handlers are assigned to app events in the Application object:

App. DocumentOpen + = Myopendoc; App. DocumentChange + = myChangeDoc;



You can use these two events now. When the Open method is called, the two events are raised at the same time. Open the hyperlink in turn read the documentation for the DocumentOpen (English) and DocumentChange (English) methods.



So, how do you know which events are available and how they are invoked by handlers? If you use ILDASM to check Word 2002 PIA (Microsoft.Office.Interop.Word.dll), you will find that you have a green inverted triangle marked in front of some types. The flag indicates that the member is an event. Figure 4 shows the help for the ILDASM tree view icon.





Figure 4:ildasm tree view icon Help





Figure 5: Using ILDASM to view events for application objects



Figure 5 shows a partial screenshot of the event for the Application object. The leftmost identifier for each row is the event name. To the right of the colon is the fully qualified type name of the event handler. For example, the DocumentBeforeSave event requires the following types of handlers:





Microsoft.Office.Interop.Word
. Applicationevents3_documentbeforesaveeventhandler





Please note that the event does not tell us any information about the signature of the event handler. Therefore, you need to look at the event handler declaration. In ILDASM, if you double-click the applicationevents3_documentbeforesaveeventhandler type, you see something like Figure 6 .






Figure 6: Viewing an event handler declaration in ILDASM



What makes us interested is the Invoke method. A function written for an event handler must have this signature. But how do you know the meaning of the parameter and the value it uses? This is the importance of Word 2002 Visual Basic documents. For DocumentBeforeSave events, the document is described as follows:





Private Sub Object_documentbeforesave (ByVal Doc as Document, SaveAsUi as
Boolean, Cancel as Boolean)





The document then describes the meaning of each parameter. Keep in mind that C # passes parameters by value by default, and Visual Basic passes parameters by reference by default. This is why the two Boolean parameters are followed by the & symbol when they are displayed in ILDASM and are marked with the keyword ref when used in C #. Similarly, subs in Visual Basic is considered a method of returning void in C #. Therefore, a handler for theDocumentsave event should resemble the following:





public static void Savehandler (Document doc, ref bool B1, ref bool B2) {
MessageBox.Show ("Saving document", "Documentsave event",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}





When you save a document by calling the SaveAs method, theDocumentBeforeSave event is raised before the document is saved.



In the next few lines of code in the SaveAs method call, you will see the following code fragment:



App. DocumentChange-= myChangeDoc;



This line of code unlocks the DocumentChange event so that the event is not raised during the call to Quit .



  how to build and run Example4.cs



To build Example4.cs, you can do the following in the Visual Studio. NET command Prompt(Visual Studio. NET commands) window:


    1. Open the directory where you saved the Example4.cs source file (for example, C:\CSOfficeSamples) and type/r after the command prompt : "C:\Office XP pias\ Microsoft.Office.Interop.Word.dll "/d:officexp Example4.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 Example4.cs. )
    2. To run Example4.exe (located in the same folder as the Example4.cs source file), double-click the program.


  Example 5: Animate the Office Assistant



Some people like Office assistants, and some hate them. In any case, Example5.cs here is just to add a little fun. This sample program also uses the assistant type information that is located in Mso.dll. The program uses two PIAs:


    • Microsoft.Office.Interop.Word.dll
    • Office.dll


Each important step in the Example5.cs source file is commented on in detail. This code is not intended to be introduced here because it is easy to understand.



  how to build and run Example5.cs



To build Example5.cs, you can do the following in the Visual Studio. NET command Prompt(Visual Studio. NET commands) window:


    1. Open the directory where you saved the Example5.cs source file (for example, the C:\CSOfficeSamples directory) and type /r after the command prompt : "C:\Office XP pias\ Microsoft.Office.Interop.Word.dll "/r: C:\Office XP pias\office.dll" Example5.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/r:d rive:\< installation path >\office.dll Example5.cs. )
    2. To run Example5.exe (located in the same folder as the Example5.cs source file), double-click the program.


  Example 6: Default properties and Indexed properties



This example (Excel1.cs) takes advantage of the fact that Word 2002 rarely uses default properties and indexed properties, and Excel 2002 often uses them.



Like all Office XP interop codes, the example program starts with instantiating the Application object. After you create a workbook and worksheet, you create an array of strings to hold the column headers. After you create the array, you will see the following code fragment:



Wksrange = Wks.get_range ("A2", "D2");



This code gets the Range object for cell A2 to D2. But since the worksheet has a Range property, why do I need to call the Access function directly? And why doesn't it make grammatical mistakes as usual?



Unlike visual Basic and Visual C + +, C # does not have a syntax structure that applies to indexed properties. To use indexed properties in C #, you must call the Access function directly. The _worksheet.range attribute is a good example. To get the value of the Range property in Visual C + +, the code looks like this:



MyRange = myworksheet->range["A2", "D2"];



To perform the same action in C #, the code should look like this:



MyRange = Myworksheet.get_range ("A2", "D2");



Setting the Range property instead of assigning it a value is a call to the set access function:



Myworksheet.set_range ("A2", "D2", MyRange);



The range.value property in Microsoft Excel 2000 is a general property, but in Excel 2002 it becomes an indexed property. This is why you should enclose this property in #if officexp statement in this sample program.



  _workbook.worksheets has the so-called default properties. Default properties are considered to be properties in an interop assembly that are named Item. You usually have to specify an Item member to use the default property from C #, but in an Excel library, TLBIMP can create an access function called get__default or set__default with only a small amount of code. If these two access functions exist, C # can use the Index builder syntax instead of calling the access function directly. The two lines of code in this example are as follows:





_worksheet wks2 = (_worksheet) wkb.worksheets["Market share!"];
((_worksheet) wkb.worksheets["Market share!"] ). Name = "Fred";

   how to build and run Excel1.cs





To build Excel1.cs, you can do the following in the Visual Studio. NET command Prompt(Visual Studio. NET commands) window:


    1. Open the directory where you saved the Excel1.cs source file (for example, the C:\CSOfficeSamples directory) and type/r after the command prompt : C:\Office XP pias\ Microsoft.Office.Interop.Excel.dll "/d:officexp Excel1.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.excel.dll/d:o Fficexp Excel1.cs. )
    2. To run Excel1.exe (located in the same folder as the Excel1.cs source file), double-click the program.


  Summary



C # COM Interop is a useful tool because it allows you to use existing objects directly without rewriting the code for those objects. This article can help you take advantage of existing COM object code.





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.