Home > Articles > Programming > Windows Programming

This chapter is from the book

Office Automation Executables

We now consider each of these three patterns of Office solutions in more detail. Office solutions that use the automation executable pattern start up an Office application in a very straightforward manner—by creating a new instance of the Application object associated with the Office application. Because the automation executable controls the Office application, the automation executable runs code at startup and any time thereafter when executing control returns to the automation executable.

When an automation executable uses new to create an Application object, the automation executable controls the lifetime of the application by holding the created Application object in a variable. Office determines whether it can shut down by determining the reference count or number of clients that are using its Application object.

In Listing 2-1, as soon as new is used to create the myExcelApp variable, Excel starts and adds one to its count of clients that it knows are holding a reference to Excel's Application object. When the myExcelApp variable goes out of scope (when Main exits) .NET garbage collection releases the object and Excel is notified that the console application no longer needs Excel's Application object. This causes Excel's count of clients holding a reference to Excel's Application object to go to zero and Excel exits as no clients are using Excel anymore.

When you create an Office application by creating a new instance of the Application object, the application starts up without showing its window. This is useful because you can automate the application without distracting the user by popping up windows. If you need to show the application window, you can set the Visible property of the Application object to true. If you make the main window visible, the user controls the lifetime of the application. In Excel, the application will not exit until the user quits the application and your variable holding the Excel Application object is garbage collected. Word behaves differently—the application exits when the user quits the application even if a variable is still holding an instance of the Word Application object.

Listing 2-1 sets the status bar of Excel to say "Hello World" and opens a new blank workbook in Excel by calling the Add method of Excel's Workbooks collection. Chapters 3 through 5 cover the Excel object model in more detail.

Listing 2-1: Automation of a Excel via a console application.

using System;
using Excel = Microsoft.Office.Interop.Excel;
using System.Windows.Forms;

namespace ConsoleApplication
{
 class Program
 {
  static bool exit = false;
  
  static void Main(string[] args)
  {
   Excel.Application myExcelApp = new Excel.Application();
   myExcelApp.Visible = true;
   myExcelApp.StatusBar = "Hello World";
   myExcelApp.Workbooks.Add(System.Type.Missing);

   myExcelApp.SheetBeforeDoubleClick += new Excel.AppEvents_SheetBeforeDoubleClickEventHandler(myExcelApp_SheetBeforeDoubleClick);

   while (exit == false)
    System.Windows.Forms.Application.DoEvents();
  }

  static void myExcelApp_SheetBeforeDoubleClick(object Sh, Microsoft.Office.Interop.Excel.Range Target, ref bool Cancel)
  {
   exit = true;
  }
 }
}

Listing 2-1 also illustrates how an automation executable can yield time back to the Office application. A reference to the System.Windows.Forms assembly must be added to the project. After a event handlers are hooked up, System.Windows.Forms.Application.DoEvents() is called in a loop to allow the Excel application to run normally. If the user double clicks on a cell, Office yields time back to the event handler in the automation executable. In the handler for the double click event, we set the static variable exit to true which will cause the loop calling DoEvents to exit and the automation executable to exit.

You can see the lifetime management of Excel in action by running the automation executable in Listing 2-1 and exiting Excel without double clicking on a cell. Excel will continue to run in a hidden state, waiting for the console application to release its reference to Excel's Application object.

Creating a Console Application that Automates Word

In this section, we are going to walk through the creation of a simple console application that automates Word. A wiki is a kind of online encyclopedia that users can contribute to. For an example, see http://www.officewiki.net for a wiki that documents the Office PIAs. Wikis use simple, easy-to-edit text files that any visitor to the wiki can edit without having to know HTML. These text files have simple representations of even complex elements like tables. Our console application will read a simple text file that specifies a table in wiki text format. It will then automate Word to create a Word table that matches the text file specification.

In the wiki text format, a table that looks like Table 2-1 is specified by the text in Listing 2-2.

Table 2-1: A simple table showing the properties and methods of Word's Add-in object.

Property or Method

Name

Return Type

Property

Application

Application

Property

Autoload

Boolean

Property

Compiled

Boolean

Property

Creator

Int32

Method

Delete

Void

Property

Index

Int32

Property

Installed

Boolean

Property

Name

String

Property

Parent

Object

Property

Path

String

Listing 2-2: A Wiki text representation of Table 1-4.

||Property or Method||Name||Return Type||
||Property||Application||Application||
||Property||Autoload||Boolean||
||Property||Compiled||Boolean||
||Property||Creator||Int32||
||Method||Delete||Void||
||Property||Index||Int32||
||Property||Installed||Boolean||
||Property||Name||String||
||Property||Parent||Object||
||Property||Path||String||

We will use Visual Studio .NET 2005 to create a console application. After launching Visual Studio, choose New Project... from the File menu. The new project dialog shows a variety of project types. Select the Visual C# node from the list of project types and select the Windows node under the Visual C# node. This is slightly counter intuitive as there is an Office node available as well, but the Office node only shows VSTO code behind document projects and the VSTO Outlook add-in project.

After you select the Windows node, you will see in the window to the right the available templates. Select the Console Application template. Name your console application project then press the OK button to create your project. In Figure 2-1 we've created a console application called WordWiki. Note that the new project dialog can have a different appearance than the one shown in Figure 2-1 depending on the profile you are using. In this book, we assume you are using the Visual C# Development Settings profile. You can change your profile by choosing Import and Export Settings... from the Tools menu.

Figure 1

Figure 2-1: Creating a console application from the New Project dialog.

Once you press the OK button, Visual Studio creates a console application project for you. Visual Studio displays the contents of the project in the Solution Explorer window as shown in Figure 2-2.

Figure 2

Figure 2-2: The Console application project "WordWiki" shown in Solution Explorer.

By default, a newly created console application references the assemblies System, System.Data, and System.Xml. We also need to add a reference to the Word 2003 PIA. We do this by right clicking on the References folder and choosing Add Reference... from the popup menu that appears. This shows the Add Reference dialog in Figure 2-3. Click on the COM tab and select the Microsoft Word 11.0 Object Library to add a reference to the Word 2003 PIA. Then click the OK button.

Figure 3

Figure 2-3: Adding a reference to the Microsoft Word 2003 PIA.

Visual Studio adds the reference to the Word 2003 PIA and adds additional references to the stdole, VBIDE, and Microsoft.Office.Core PIAs as shown in Figure 2-4. These additional PIAs are ones that the Word PIA depends on. Stdole is a PIA that contains the definition of some of the types that COM object models need. VBIDE is the PIA for the object model associated with the VBA editor integrated into Office. Microsoft.Office.Core (office.dll) is the PIA for common functionality shared by all the Office applications such as the object model for the toolbars and menus.

Figure 04

Figure 2-4: When you add the Word 2003 PIA, dependent PIA references are automatically added to the project.

Now that the proper references have been added to our console application, let's start writing code. Double click on Program.cs in the Solution Explorer window to edit the main source code file for the console application. If you have outlining turned on, you will see the text "using ..." at the top of the Program.cs file with a + sign next to it. Click on the + sign to expand out the code where the using directives are placed. Add the following three using directives so we can use objects from the Word PIA and the Microsoft.Office.Core PIA as well as classes in the System.IO namespace.

using Office = Microsoft.Office.Core;
using Word = Microsoft.Office.Interop.Word;
using System.IO;

We are now ready to write some real code that automates Word to create a table after reading a text input file in the wiki table format. The entire listing of our program is shown in Listing 2-3. Rather than explain every line of code in that listing, we will focus on the lines of code that automate Word. We assume the reader has some knowledge of how to read a text file in .NET and parse a string via the Split method. We will briefly touch on some objects in the Word object model here, but Chapters 6 through 8 cover the Word object model in much more detail.

The first thing we do in Listing 2-3 is declare a new instance of the Word application object by adding this line of code to Main method of our program class.

Word.Application theApplication = new Word.Application();

Although Word.Application is an interface, we are allowed to create a new instance of this interface because the compiler knows that the Word.Application interface is associated with a COM object that it knows how to start. When Word starts in response to an automation executable creating a new instance of its application object, it starts up without showing any windows. You can automate Word in this invisible state when you want to automate Word without confusing the user by bringing up the Word window. For this example, we want to make Word show its main window, and we do so by adding this line of code:

theApplication.Visible = true;

Next, we want to create a new empty Word document into which we will generate our table. We do this by calling the Add method on the Documents collection returned by Word's application object. The Add method takes four optional parameters that we want to omit. Optional parameters in Word methods are specified as omitted by passing by reference a variable containing the special value Type.Missing. We declare a variable called missing that we set to Type.Missing and pass it by reference to each parameter we wish to omit as shown here:

object missing = Type.Missing;
Word.Document theDocument = theApplication.Documents.Add(
ref missing,
ref missing, 
ref missing, 
ref missing);

With a document created, we want to read the input text file specified by the command line argument passed to our console application. We want to parse that text file to calculate the number of columns and rows. Once we know the number of columns and rows, we use the line of code below to get a Range object from the Document object. By passing our missing variable to the optional parameters, the Range method will return a range that includes the entire text of the document.

Word.Range range = theDocument.Range(ref missing, ref missing);

We then use our Range object to add a table by calling the Add method of the Tables collection returned by the Range object. We pass the Range object again as the first parameter to the Add method to specify that we want to replace the entire contents of the document with the table. We also specify the number of rows and columns we want.

Word.Table table = range.Tables.Add(
range, 
rowCount, 
columnCount, 
ref missing, 
ref missing);

The Table object has a Cell method that takes a row and column and returns a Cell object. The Cell object has a Range property that returns a Range object for the cell in question that we can use to set the text and formatting of the cell. The code that sets the cells of the table is shown below. Note that as in most of the Office object models, the indices are 1-based meaning they start with one as the minimum value rather than being 0-based and starting with zero as the minimum value.

for (columnIndex = 1; columnIndex <= columnCount; columnIndex++)
{
 Word.Cell cell = table.Cell(rowIndex, columnIndex);
 cell.Range.Text = splitRow[columnIndex];
}

Code to set the formatting of the table by setting the table to size to fit contents and bolding the header row is shown below. We use the Row object returned by table.Rows[1] which also has a Range property that returns a Range object for the row in question. Also, we encounter code that sets the first row of the table to be bolded. One would expect to be able to write the code table.Rows[1].Range.Bold = true, but Word's object model expects an int value (0 or 1) rather than a bool. This is one of many examples you will come across where the Office object models don't match .NET guidelines because of their origins in COM.

// Format table
table.Rows[1].Range.Bold = 1;
table.AutoFitBehavior(Word.WdAutoFitBehavior.wdAutoFitContent);

Finally, there is some code at the end of the program that forces Word to quit without saving changes:

// Quit without saving changes
object saveChanges = false;
theApplication.Quit(ref saveChanges, ref missing, ref missing);

If we don't write this code, Word will stay running even after the console application exits. Once you show the Word window by setting the Application object's Visible property to true, Word puts the lifetime of the application in the hands of the end user rather than the automating program. So even when the automation executable exits, Word will continue running. To force Word to exit we must call the Quit method on Word's Application object. If this program didn't make the Word window visible—say for example it created the document with the table then saved it to a file all without showing the Word window—it would not have to call Quit because Word would exit when the program exited and released all its references to the Word objects.

To run the console application in listing 2-3, you must create a text file that contains the text in Listing 2-2. Then pass the file name of the text file as a command line argument to the console application. You can set up the debugger to do this by right clicking on the WordWiki project in Solution Explorer and choosing Properties. Then click on the Debug tab and set the Command line arguments field to the name of your text file.

Listing 2-3: The complete WordWiki implementation.

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Office = Microsoft.Office.Core;
using Word = Microsoft.Office.Interop.Word;
 
namespace WordWiki
{
 class Program
 {
  static void Main(string[] args)
  {
   Word.Application theApplication = new Word.Application();
   theApplication.Visible = true;

   object missing = System.Type.Missing;
   Word.Document theDocument = theApplication.Documents.Add(ref missing, ref missing, ref missing, ref missing);

   TextReader reader = new System.IO.StreamReader(args[0]);

   string[] separators = new string[1];
   separators[0] = "||";
   int rowCount = 0;
   int columnCount = 0;

   // Read rows and calculate number of rows and columns
   System.Collections.Generic.List<string> rowList = new System.Collections.Generic.List<string>();
   string row = reader.ReadLine();

   while (row != null)
   {
    rowCount++;
    rowList.Add(row);

    // If this is the first row, calculate the number of columns
    if (rowCount == 1)
    {
     string[] splitHeaderRow = row.Split(separators, StringSplitOptions.None);
     columnCount = splitHeaderRow.Length - 2; // Ignore the first & last separator
    }

    row = reader.ReadLine();
   }

   // Create a table
   Word.Range range = theDocument.Range(ref missing, ref missing);
   Word.Table table = range.Tables.Add(range, rowCount, columnCount, ref missing, ref missing);
 
   // Populate table
   int columnIndex = 1;
   int rowIndex = 1;

   foreach (string r in rowList)
   {
    string[] splitRow = r.Split(separators, StringSplitOptions.None);

    for (columnIndex = 1; columnIndex <= columnCount; columnIndex++)
    {
     Word.Cell cell = table.Cell(rowIndex, columnIndex);
     cell.Range.Text = splitRow[columnIndex];
    }

    rowIndex++;
   }

   // Format table
   table.Rows[1].Range.Bold = 1;
   table.AutoFitBehavior(Word.WdAutoFitBehavior.wdAutoFitContent);

   // Wait for input from the command line before exiting
   System.Console.WriteLine("The table has been generated.");
   System.Console.ReadLine();

   // Quit without saving changes
   object saveChanges = false;
   theApplication.Quit(ref saveChanges, ref missing, ref missing);
  }
 }
}

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020