Home > Articles > Programming > Windows Programming

  • Print
  • + Share This
This chapter is from the book

Automating Excel

At the most fundamental level, automating Excel from .NET solutions does not differ from automating Excel from Classic VB. What must be taken into consideration is that the .NET Framework cannot communicate directly with Excel because of differences between .NET technology and the COM technology Excel is built on. It is necessary to create a bridge between these two technologies for us to be able to automate Excel from the .NET platform. The bridge between .NET and COM is mostly provided by features contained in two .NET Framework namespaces: System.Runtime.InteropServices and System.EnterpriseServices. However, there are additional components required to allow interoperability that we need to discuss further.

Primary Interop Assembly (PIA)

When we set a reference to a COM type library in a .NET solution, the VS IDE automatically creates a default Interop Assembly (IA). The auto-generated IA is a .NET-based assembly that acts as a wrapper for the COM type library. The IA provides us with basic access to the COM type library, and it contains type definitions (as metadata) of types implemented by COM. A Primary Interop Assembly (PIA) is a prebuilt, vendor-supplied assembly. The difference between an IA and a PIA is more or less semantic.

Microsoft has released PIAs for all Excel versions beginning with Excel 2002 as part of the Microsoft Office PIAs. The PIAs have strong names and are digitally signed by Microsoft. The use of strong names makes it possible to install PIAs in the Global Assembly Cache (GAC). The GAC is a machinewide .NET assembly cache for the CLR. Assemblies that should have only one version on the system should be installed in the GAC.

One important point to understand is that only one version of the PIAs can be used on a system, although multiple versions can be installed side by side in the GAC. In addition, PIAs are registered in the Windows registry. If multiple versions of the PIAs are installed, only the latest version is registered, and the entries for any previous version are overwritten.

When we set a reference to Excel in a .NET solution the VS IDE reads the registry and adds a reference to the PIA instead of generating a new IA. This guarantees that we always use the PIAs if they are available. As a practical matter, when we are automating Excel from .NET we are always developing against the PIA and not the Excel COM type library.

The PIAs are optimized for Excel and you should always use the official Microsoft versions. The PIAs are also Excel version-specific. This means you cannot automate Excel 2002 using the PIA for Excel 2003. Therefore, you must be sure the correct version of the PIA is installed on your development computer. Whether or not the PIA is already installed on a computer depends on the following:

  • For Excel 2002 on Windows XP or Windows Vista you need to manually download and install the redistributable PIA package from the Microsoft Web site. If you run Windows XP, then the .NET Framework must be installed prior to installing the PIA package.
  • For Excel 2003 or Excel 2007 on Windows XP, if Microsoft Office has been installed before the .NET Framework, then you must install the PIA package manually. You can either download the redistributable PIA package from the Microsoft Web site or install it from the Office CD.
  • For Excel 2003 or Excel 2007 on Windows Vista you do not need to take any action at all. Because version 3.0 of the .NET Framework is shipped with Windows Vista, the PIAs are automatically installed when Office is installed.

Since no official PIA exists for Excel 2000, we must compile our own IA using the TlbImp.exe tool that is shipped as part of the .NET Framework SDK. It takes the Excel9.olb file as its input and generates a .NET assembly as its output. When automating Excel from .NET you should always develop against the earliest versions of the PIA and Excel that you plan to target and the earliest version of the .NET Framework you intend to use.

You need to be aware of the code execution overhead for all kinds of .NET solutions, especially when it comes to interaction between .NET and COM. Compared with Classic VB, .NET solutions require more components and therefore require more overhead to run. These components include

  • The COM interop layer (PIA)
  • The CLR
  • The .NET Framework

As we see in the next section, there are additional aspects we need to consider to maintain acceptable performance for .NET solutions that automate Excel. If high performance is critical to your solution you may even consider using Classic VB if it is available and is an acceptable development platform.

Using Excel Objects in .NET Solutions

Create a Windows Forms solution and name it "Automate Excel." Add a button to the form and name it "Automate Excel." Next, add a reference to the Excel 2003 PIA or later. Choose Project > Add Reference... from the VS IDE menu to display the Add Reference dialog. Select the COM tab and scroll down to locate the Microsoft Excel 11.0 Object Library as shown in Figure 24-20. The reference is added when you close the dialog by clicking the OK button.

Figure 24-20

Figure 24-20 Adding a reference to the Excel Object Library

Choose Project > Automate Excel Properties... from the VS IDE menu. Select the References tab, and you see that three new Excel-related references have been added: the Excel Object Library, the Office Object Library, and the VBA Extensibility Object Library. Figure 24-21 shows the current list of references in the solution.

Figure 24-21

Figure 24-21 References in the automate Excel solution

The System references are added by default. These give us access to the most commonly used .NET Framework class libraries. The imported namespaces are automatically included in all new .NET solutions. These are globally available in a solution. Open the Windows Form class module. When working with namespaces like Excel it is a good development practice to create a namespace alias for it at the top of the code module. We also add another Imports statement that is required as shown in Listing 24-26.

Listing 24-26. Namespace Alias and Imports Statements

'Namespace alias for Excel.
Imports Excel = Microsoft.Office.Interop.Excel

'To release COM objects and catch COM errors.
Imports System.Runtime.InteropServices

Declaring and instantiating some Excel COM objects, like Workbook and Range objects, requires that we cast the object reference to the precise type using the CType function. This is because the Option Strict setting prevents us from using code that might fail at runtime due to type conversion errors. The VS IDE actually helps us with this task by visually marking the objects that need to be cast.

Next, add a Click event handler for the button. Listing 24-27 shows the code required to get the Excel automation started. Put this code in the button's Click event. As you can see, we implemented an SEH but intentionally left out any exception handling code. At this stage we also did not add the code required to release any of the Excel objects we used.

Listing 24-27. Declare and Instantiate Excel Objects

Dim xlApp As Excel.Application = Nothing
Dim xlWkbNew As Excel.Workbook = Nothing
Dim xlWksMain As Excel.Worksheet = Nothing
Dim xlRngData As Excel.Range = Nothing
Dim sData() As String = {"Hello", "World", "!"}


Try
    'Instantiate a new Excel session.
    xlApp = New Excel.Application

    'Add a new workbook.
    xlWkbNew = xlApp.Workbooks.Add

    'Reference the first worksheet in the workbook.
    xlWksMain = CType(xlWkbNew.Worksheets(Index:=1), _
                        Excel.Worksheet)

    'Reference the range to which we will write some
    data to.
    xlRngData = CType(xlWksMain.Range("A1:C1"),  _
                        Excel.Range)

    'Write the data to the range.
    xlRngData.Value = sData

    'Save the workbook.
    xlWkbNew.SaveAs(Filename:="c:\Test\New.xls")

    'Make Excel visible for the user.
    With xlApp
        .UserControl = True
        .Visible = True
    End With

Catch COMex As COMException

Catch ex As Exception

End Try

As shown in Listing 24-27, we must explicitly use the Value property of the Excel Range object in VB.NET. This is because VB.NET does not recognize default properties.

Whenever Excel objects are instantiated at runtime the CLR creates so called Runtime Callable Wrapper (RCW) for each underlying COM object in the memory. It is the group of RCWs that constitute the runtime proxies, or bridges, between a .NET solution and the COM type libraries it references. This is important to keep in mind because the more Excel COM objects we use, the more memory our solution consumes at runtime. It is a good development practice to clean up the RCW reference counts so we don't end up with a large number orphaned RCWs.

Let's take a closer look at the code in Listing 24-27. Initially it looks like we are only using four objects: the Application object, the Workbook object, the Worksheet object, and the Range object. But we indirectly reference the Workbooks collection, the Worksheets collection, and the Range collection, so we actually use seven objects. The objects used indirectly are out of our control but must be managed anyway.

On the .NET platform the Garbage Collector (GC), is responsible for all memory management. The GC uses a managed memory scheme that periodically traces live references. When the trace is complete, all unreachable objects are released, and the GC reclaims the memory they previously used. The GC operates in a nondeterministic manner, so we never know exactly when it will perform its memory management tasks.

For pure .NET solutions this is not a problem, but it becomes an issue when trying to release COM objects properly. When releasing Excel objects we must be sure to release all the objects we have used. Otherwise, we may end up in a situation where Excel remains in memory and continues to consume resources even after our application has ended.

The first step in a practical solution is to explicitly call the GC from our .NET code. Calling the GC is a time-consuming process, but one that may be necessary when automating Excel because it is the only way to release all the Excel COM objects referenced indirectly. Each RCW has a finalizer that is responsible for releasing its COM object from memory. This finalizer needs to be called twice to fully remove the COM object from memory. Therefore, if we call the GC twice it releases our three indirectly referenced Excel objects.

The second step in a practical solution is to call the Marshal.FinalReleaseComObject method for every Excel COM object. Note that Excel objects must be released in the reverse order in which they were created, with the Excel Application object released last. Listing 24-28 shows the code in our solution used to release all the Excel COM objects. This should normally be performed when we are closing the application.

Listing 24-28. Releasing Excel COM Objects with a Function

      'In the calling sub procedure.
      '...
        Finally

            'Calling the Garbage Collector twice.
            GC.Collect()
            GC.WaitForPendingFinalizers()
            GC.Collect()
            GC.WaitForPendingFinalizers()

            'Releasing the Excel objects.
            ReleaseCOMObject(xlRngData)
            ReleaseCOMObject(xlWksMain)
            ReleaseCOMObject(xlWkbNew)
            ReleaseCOMObject(xlApp)

        End Try

    End Sub

    Private Sub ReleaseCOMObject(ByVal oxlObject As Object)
        Try
            Marshal.ReleaseComObject(oxlObject)
            oxlObject = Nothing
        Catch ex As Exception
            oxlObject = Nothing
        End Try

    End Sub

Note how we use the custom ReleaseCOMObject function to release the Excel objects and set them to Nothing. This example also shows why the Finally block is so useful; it ensures that the code required to clean up our Excel objects will always run.

The Automate Excel example can be found on the companion CD in \Concepts\Ch24 - Excel & VB.NET\Automate Excel folder. If you just want to run the example, the Automate Excel executable file can be found in the \Concepts\Ch24 - Excel & VB.NET\Excel Automate\Excel Automate\bin\Debug folder on the CD.

Using Late Binding

Whenever possible, we should use early binding and declare all variables as specific types. The reasons for this are simple:

  • Our .NET solutions run faster because it is not necessary to perform type conversion on any variables.
  • The compiler can detect and display exceptions and therefore prevent runtime exceptions.
  • We get IntelliSense support and dynamic help during the development process.

Unfortunately, it is common for developers to have the latest version of an application such as Microsoft Office while end users have earlier versions. However, given access to desktop virtualization software such as WMware (commercial software) and Microsoft Virtual PC (free tool) it is now much easier for developers to use the same versions of software as the end users they develop for. This makes it possible for developers to use early binding in their applications.

  • + Share This
  • 🔖 Save To Your Account