Walkthrough: Embedding Type Information from Microsoft Office Assemblies (C# and Visual Basic)

If you embed type information in an application that references COM objects, you can eliminate the need for a primary interop assembly (PIA). Additionally, the embedded type information enables you to achieve version independence for your application. That is, your program can be written to use types from multiple versions of a COM library without requiring a specific PIA for each version. This is a common scenario for applications that use objects from Microsoft Office libraries. Embedding type information enables the same build of a program to work with different versions of Microsoft Office on different computers without the need to redeploy either the program or the PIA for each version of Microsoft Office.

In this walkthrough, you will perform the following tasks:

  • Create an application that uses Automation objects from Microsoft Office and embeds the type information from the Microsoft Office COM libraries.

  • Publish and run the application with multiple versions of Microsoft Office without a PIA.

Note

Your computer might show different names or locations for some of the Visual Studio user interface elements in the following instructions. The Visual Studio edition that you have and the settings that you use determine these elements. For more information, see Visual Studio Settings.

Prerequisites

This walkthrough requires the following:

  • A computer on which Visual Studio and Microsoft Excel are installed.

  • A computer on which .NET Framework 4 and a different version of Excel are installed.

To create an application that works with multiple versions of Microsoft Office

  1. Start Visual Studio on a computer on which Excel is installed.

  2. On the File menu, point to New and then click Project.

  3. In the New Project dialog box, in the Project Types pane, make sure that Windows is selected. Select Console Application in the Templates pane. In the Name box, type CreateExcelWorkbook, and then click OK. The new project is created.

  4. If you are using Visual Basic, right-click the CreateExcelWorkbook project and then click Properties. Click the References tab. Click the Add button. If you are using Visual C#, in Solution Explorer, right-click the References folder and then click Add Reference.

  5. On the .NET tab, click the most recent version of Microsoft.Office.Interop.Excel. For example, Microsoft.Office.Interop.Excel 14.0.0.0. Click OK.

  6. In the list of references for the CreateExcelWorkbook project, select the reference for Microsoft.Office.Interop.Excel that you added in the previous step. In the Properties window, make sure that the Embed Interop Types property is set to True.

    Note

    The application created in this walkthrough runs with different versions of Microsoft Office because of the embedded interop type information. If the Embed Interop Types property is set to False, you must include a PIA for each version of Microsoft Office that the application will run with.

  7. If you are using Visual Basic, double-click the Module1.vb file. If you are using Visual C#, double-click the Program.cs file. Replace the code in the file with the following code.

    Imports Excel = Microsoft.Office.Interop.Excel
    
    Module Module1
    
        Sub Main()
            Dim values = {4, 6, 18, 2, 1, 76, 0, 3, 11}
    
            CreateWorkbook(values, "C:\SampleFolder\SampleWorkbook.xls")
        End Sub
    
        Sub CreateWorkbook(ByVal values As Integer(), ByVal filePath As String)
            Dim excelApp As Excel.Application = Nothing
            Dim wkbk As Excel.Workbook
            Dim sheet As Excel.Worksheet
    
            Try
                ' Start Excel and create a workbook and worksheet.
                excelApp = New Excel.Application
                wkbk = excelApp.Workbooks.Add()
                sheet = CType(wkbk.Sheets.Add(), Excel.Worksheet)
                sheet.Name = "Sample Worksheet"
    
                ' Write a column of values.
                ' In the For loop, both the row index and array index start at 1.
                ' Therefore the value of 4 at array index 0 is not included.
                For i = 1 To values.Length - 1
                    sheet.Cells(i, 1) = values(i)
                Next
    
                ' Suppress any alerts and save the file. Create the directory 
                ' if it does not exist. Overwrite the file if it exists.
                excelApp.DisplayAlerts = False
                Dim folderPath = My.Computer.FileSystem.GetParentPath(filePath)
                If Not My.Computer.FileSystem.DirectoryExists(folderPath) Then
                    My.Computer.FileSystem.CreateDirectory(folderPath)
                End If
                wkbk.SaveAs(filePath)
        Catch
    
            Finally
                sheet = Nothing
                wkbk = Nothing
    
                ' Close Excel.
                excelApp.Quit()
                excelApp = Nothing
            End Try
    
        End Sub
    End Module
    
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.IO;
    using Excel = Microsoft.Office.Interop.Excel;
    
    namespace CreateExcelWorkbook
    {
        class Program
        {
            static void Main(string[] args)
            {
                int[] values = {4, 6, 18, 2, 1, 76, 0, 3, 11};
    
                CreateWorkbook(values, @"C:\SampleFolder\SampleWorkbook.xls");
            }
    
            static void CreateWorkbook(int[] values, string filePath)
            {
                Excel.Application excelApp = null;
                Excel.Workbook wkbk;
                Excel.Worksheet sheet;
    
                try
                {
                        // Start Excel and create a workbook and worksheet.
                        excelApp = new Excel.Application();
                        wkbk = excelApp.Workbooks.Add();
                        sheet = wkbk.Sheets.Add() as Excel.Worksheet;
                        sheet.Name = "Sample Worksheet";
    
                        // Write a column of values.
                        // In the For loop, both the row index and array index start at 1.
                        // Therefore the value of 4 at array index 0 is not included.
                        for (int i = 1; i < values.Length; i++)
                        {
                            sheet.Cells[i, 1] = values[i];
                        }
    
                        // Suppress any alerts and save the file. Create the directory 
                        // if it does not exist. Overwrite the file if it exists.
                        excelApp.DisplayAlerts = false;
                        string folderPath = Path.GetDirectoryName(filePath);
                        if (!Directory.Exists(folderPath))
                        {
                            Directory.CreateDirectory(folderPath);
                        }
                        wkbk.SaveAs(filePath);
                }
                catch
                {
                }
                finally
                {
                    sheet = null;
                    wkbk = null;
    
                    // Close Excel.
                    excelApp.Quit();
                    excelApp = null;
                }
            }
        }
    }
    
  8. Save the project.

  9. Press CTRL+F5 to build and run the project. Verify that an Excel workbook has been created at the location specified in the example code: C:\SampleFolder\SampleWorkbook.xls.

To publish the application to a computer on which a different version of Microsoft Office is installed

  1. Open the project created by this walkthrough in Visual Studio.

  2. On the Build menu, click Publish CreateExcelWorkbook. Follow the steps of the Publish Wizard to create an installable version of the application. For more information, see Publish Wizard.

  3. Install the application on a computer on which .NET Framework 4 and a different version of Excel are installed.

  4. When the installation is finished, run the installed program.

  5. Verify that an Excel workbook has been created at the location specified in the sample code: C:\SampleFolder\SampleWorkbook.xls.

See Also

Tasks

Walkthrough: Embedding Types from Managed Assemblies (C# and Visual Basic)

Reference

/link (Visual Basic)

/link (C# Compiler Options)

Change History

Date

History

Reason

September 2011

Added a code comment about the value at array index 0.

Customer feedback.