How to access Office interop objects - C# (2024)

  • Article

C# has features that simplify access to Office API objects. The new features include named and optional arguments, a new type called dynamic, and the ability to pass arguments to reference parameters in COM methods as if they were value parameters.

In this article, you use the new features to write code that creates and displays a Microsoft Office Excel worksheet. You write code to add an Office Word document that contains an icon that is linked to the Excel worksheet.

To complete this walkthrough, you must have Microsoft Office Excel 2007 and Microsoft Office Word 2007, or later versions, installed on your computer.

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 Personalizing the IDE.

Important

VSTO (Visual Studio Tools for Office) relies on the .NET Framework. COM add-ins can also be written with the .NET Framework. Office Add-ins cannot be created with .NET Core and .NET 5+, the latest versions of .NET. This is because .NET Core/.NET 5+ cannot work together with .NET Framework in the same process and may lead to add-in load failures. You can continue to use .NET Framework to write VSTO and COM add-ins for Office. Microsoft will not be updating VSTO or the COM add-in platform to use .NET Core or .NET 5+. You can take advantage of .NET Core and .NET 5+, including ASP.NET Core, to create the server side of Office Web Add-ins.

To create a new console application

  1. Start Visual Studio.
  2. On the File menu, point to New, and then select Project. The New Project dialog box appears.
  3. In the Installed Templates pane, expand C#, and then select Windows.
  4. Look at the top of the New Project dialog box to make sure to select .NET Framework 4 (or later version) as a target framework.
  5. In the Templates pane, select Console Application.
  6. Type a name for your project in the Name field.
  7. Select OK.

The new project appears in Solution Explorer.

To add references

  1. In Solution Explorer, right-click your project's name and then select Add Reference. The Add Reference dialog box appears.
  2. On the Assemblies page, select Microsoft.Office.Interop.Word in the Component Name list, and then hold down the CTRL key and select Microsoft.Office.Interop.Excel. If you don't see the assemblies, you may need to install them. See How to: Install Office Primary Interop Assemblies.
  3. Select OK.

To add necessary using directives

In Solution Explorer, right-click the Program.cs file and then select View Code. Add the following using directives to the top of the code file:

using Excel = Microsoft.Office.Interop.Excel;using Word = Microsoft.Office.Interop.Word;

To create a list of bank accounts

Paste the following class definition into Program.cs, under the Program class.

public class Account{ public int ID { get; set; } public double Balance { get; set; }}

Add the following code to the Main method to create a bankAccounts list that contains two accounts.

// Create a list of accounts.var bankAccounts = new List<Account> { new Account { ID = 345678, Balance = 541.27 }, new Account { ID = 1230221, Balance = -127.44 }};

To declare a method that exports account information to Excel

  1. Add the following method to the Program class to set up an Excel worksheet. Method Add has an optional parameter for specifying a particular template. Optional parameters enable you to omit the argument for that parameter if you want to use the parameter's default value. Because you didn't supply an argument, Add uses the default template and creates a new workbook. The equivalent statement in earlier versions of C# requires a placeholder argument: ExcelApp.Workbooks.Add(Type.Missing).
static void DisplayInExcel(IEnumerable<Account> accounts){ var excelApp = new Excel.Application(); // Make the object visible. excelApp.Visible = true; // Create a new, empty workbook and add it to the collection returned // by property Workbooks. The new workbook becomes the active workbook. // Add has an optional parameter for specifying a particular template. // Because no argument is sent in this example, Add creates a new workbook. excelApp.Workbooks.Add(); // This example uses a single workSheet. The explicit type casting is // removed in a later procedure. Excel._Worksheet workSheet = (Excel.Worksheet)excelApp.ActiveSheet;}

Add the following code at the end of DisplayInExcel. The code inserts values into the first two columns of the first row of the worksheet.

// Establish column headings in cells A1 and B1.workSheet.Cells[1, "A"] = "ID Number";workSheet.Cells[1, "B"] = "Current Balance";

Add the following code at the end of DisplayInExcel. The foreach loop puts the information from the list of accounts into the first two columns of successive rows of the worksheet.

var row = 1;foreach (var acct in accounts){ row++; workSheet.Cells[row, "A"] = acct.ID; workSheet.Cells[row, "B"] = acct.Balance;}

Add the following code at the end of DisplayInExcel to adjust the column widths to fit the content.

workSheet.Columns[1].AutoFit();workSheet.Columns[2].AutoFit();

Earlier versions of C# require explicit casting for these operations because ExcelApp.Columns[1] returns an Object, and AutoFit is an Excel Range method. The following lines show the casting.

((Excel.Range)workSheet.Columns[1]).AutoFit();((Excel.Range)workSheet.Columns[2]).AutoFit();

C# converts the returned Object to dynamic automatically if the assembly is referenced by the EmbedInteropTypes compiler option or, equivalently, if the Excel Embed Interop Types property is true. True is the default value for this property.

To run the project

Add the following line at the end of Main.

// Display the list in an Excel spreadsheet.DisplayInExcel(bankAccounts);

Press CTRL+F5. An Excel worksheet appears that contains the data from the two accounts.

To add a Word document

The following code opens a Word application and creates an icon that links to the Excel worksheet. Paste method CreateIconInWordDoc, provided later in this step, into the Program class. CreateIconInWordDoc uses named and optional arguments to reduce the complexity of the method calls to Add and PasteSpecial. These calls incorporate two other features that simplify calls to COM methods that have reference parameters. First, you can send arguments to the reference parameters as if they were value parameters. That is, you can send values directly, without creating a variable for each reference parameter. The compiler generates temporary variables to hold the argument values, and discards the variables when you return from the call. Second, you can omit the ref keyword in the argument list.

The Add method has four reference parameters, all of which are optional. You can omit arguments for any or all of the parameters if you want to use their default values.

The PasteSpecial method inserts the contents of the Clipboard. The method has seven reference parameters, all of which are optional. The following code specifies arguments for two of them: Link, to create a link to the source of the Clipboard contents, and DisplayAsIcon, to display the link as an icon. You can use named arguments for those two arguments and omit the others. Although these arguments are reference parameters, you don't have to use the ref keyword, or to create variables to send in as arguments. You can send the values directly.

static void CreateIconInWordDoc(){ var wordApp = new Word.Application(); wordApp.Visible = true; // The Add method has four reference parameters, all of which are // optional. Visual C# allows you to omit arguments for them if // the default values are what you want. wordApp.Documents.Add(); // PasteSpecial has seven reference parameters, all of which are // optional. This example uses named arguments to specify values // for two of the parameters. Although these are reference // parameters, you do not need to use the ref keyword, or to create // variables to send in as arguments. You can send the values directly. wordApp.Selection.PasteSpecial( Link: true, DisplayAsIcon: true);}

Add the following statement at the end of Main.

// Create a Word document that contains an icon that links to// the spreadsheet.CreateIconInWordDoc();

Add the following statement at the end of DisplayInExcel. The Copy method adds the worksheet to the Clipboard.

// Put the spreadsheet contents on the clipboard. The Copy method has one// optional parameter for specifying a destination. Because no argument// is sent, the destination is the Clipboard.workSheet.Range["A1:B3"].Copy();

Press CTRL+F5. A Word document appears that contains an icon. Double-click the icon to bring the worksheet to the foreground.

To set the Embed Interop Types property

More enhancements are possible when you call a COM type that doesn't require a primary interop assembly (PIA) at run time. Removing the dependency on PIAs results in version independence and easier deployment. For more information about the advantages of programming without PIAs, see Walkthrough: Embedding Types from Managed Assemblies.

In addition, programming is easier because the dynamic type represents the required and returned types declared in COM methods. Variables that have type dynamic aren't evaluated until run time, which eliminates the need for explicit casting. For more information, see Using Type dynamic.

Embedding type information instead of using PIAs is default behavior. Because of that default, several of the previous examples are simplified. You don't need any explicit casting. For example, the declaration of worksheet in DisplayInExcel is written as Excel._Worksheet workSheet = excelApp.ActiveSheet rather than Excel._Worksheet workSheet = (Excel.Worksheet)excelApp.ActiveSheet. The calls to AutoFit in the same method also would require explicit casting without the default, because ExcelApp.Columns[1] returns an Object, and AutoFit is an Excel method. The following code shows the casting.

((Excel.Range)workSheet.Columns[1]).AutoFit();((Excel.Range)workSheet.Columns[2]).AutoFit();

To change the default and use PIAs instead of embedding type information, expand the References node in Solution Explorer, and then select Microsoft.Office.Interop.Excel or Microsoft.Office.Interop.Word. If you can't see the Properties window, press F4. Find Embed Interop Types in the list of properties, and change its value to False. Equivalently, you can compile by using the References compiler option instead of EmbedInteropTypes at a command prompt.

To add additional formatting to the table

Replace the two calls to AutoFit in DisplayInExcel with the following statement.

// Call to AutoFormat in Visual C# 2010.workSheet.Range["A1", "B3"].AutoFormat( Excel.XlRangeAutoFormat.xlRangeAutoFormatClassic2);

The AutoFormat method has seven value parameters, all of which are optional. Named and optional arguments enable you to provide arguments for none, some, or all of them. In the previous statement, you supply an argument for only one of the parameters, Format. Because Format is the first parameter in the parameter list, you don't have to provide the parameter name. However, the statement might be easier to understand if you include the parameter name, as shown in the following code.

// Call to AutoFormat in Visual C# 2010.workSheet.Range["A1", "B3"].AutoFormat(Format: Excel.XlRangeAutoFormat.xlRangeAutoFormatClassic2);

Press CTRL+F5 to see the result. You can find other formats in the listed in the XlRangeAutoFormat enumeration.

Example

The following code shows the complete example.

using System.Collections.Generic;using Excel = Microsoft.Office.Interop.Excel;using Word = Microsoft.Office.Interop.Word;namespace OfficeProgrammingWalkthruComplete{ class Walkthrough { static void Main(string[] args) { // Create a list of accounts. var bankAccounts = new List<Account> { new Account { ID = 345678, Balance = 541.27 }, new Account { ID = 1230221, Balance = -127.44 } }; // Display the list in an Excel spreadsheet. DisplayInExcel(bankAccounts); // Create a Word document that contains an icon that links to // the spreadsheet. CreateIconInWordDoc(); } static void DisplayInExcel(IEnumerable<Account> accounts) { var excelApp = new Excel.Application(); // Make the object visible. excelApp.Visible = true; // Create a new, empty workbook and add it to the collection returned // by property Workbooks. The new workbook becomes the active workbook. // Add has an optional parameter for specifying a particular template. // Because no argument is sent in this example, Add creates a new workbook. excelApp.Workbooks.Add(); // This example uses a single workSheet. Excel._Worksheet workSheet = excelApp.ActiveSheet; // Earlier versions of C# require explicit casting. //Excel._Worksheet workSheet = (Excel.Worksheet)excelApp.ActiveSheet; // Establish column headings in cells A1 and B1. workSheet.Cells[1, "A"] = "ID Number"; workSheet.Cells[1, "B"] = "Current Balance"; var row = 1; foreach (var acct in accounts) { row++; workSheet.Cells[row, "A"] = acct.ID; workSheet.Cells[row, "B"] = acct.Balance; } workSheet.Columns[1].AutoFit(); workSheet.Columns[2].AutoFit(); // Call to AutoFormat in Visual C#. This statement replaces the // two calls to AutoFit. workSheet.Range["A1", "B3"].AutoFormat( Excel.XlRangeAutoFormat.xlRangeAutoFormatClassic2); // Put the spreadsheet contents on the clipboard. The Copy method has one // optional parameter for specifying a destination. Because no argument // is sent, the destination is the Clipboard. workSheet.Range["A1:B3"].Copy(); } static void CreateIconInWordDoc() { var wordApp = new Word.Application(); wordApp.Visible = true; // The Add method has four reference parameters, all of which are // optional. Visual C# allows you to omit arguments for them if // the default values are what you want. wordApp.Documents.Add(); // PasteSpecial has seven reference parameters, all of which are // optional. This example uses named arguments to specify values // for two of the parameters. Although these are reference // parameters, you do not need to use the ref keyword, or to create // variables to send in as arguments. You can send the values directly. wordApp.Selection.PasteSpecial(Link: true, DisplayAsIcon: true); } } public class Account { public int ID { get; set; } public double Balance { get; set; } }}

See also

  • Type.Missing
  • dynamic
  • Named and Optional Arguments
  • How to use named and optional arguments in Office programming
How to access Office interop objects - C# (2024)

FAQs

How to add Microsoft Office Interop Excel in C#? ›

To add references
  1. In Solution Explorer, right-click your project's name and then select Add Reference. The Add Reference dialog box appears.
  2. On the Assemblies page, select Microsoft. Office. Interop. Word in the Component Name list, and then hold down the CTRL key and select Microsoft. Office. Interop. Excel. ...
  3. Select OK.
Feb 28, 2023

How to read Excel using Interop in C#? ›

Steps to read and write data from Excel using C#
  1. Step 1: Create a new C# project in Visual Studio. ...
  2. Step 2: Add COM Component Reference i.e. Excel 14 Object. ...
  3. Step 3: Import the namespaces in C# code. ...
  4. Step 4: Write Data to Excel File. ...
  5. Step 5: Read Data from Excel File. ...
  6. Step 6: Run the C# Program.
Mar 6, 2023

What is an interop library in C#? ›

Interoperability enables you to preserve and take advantage of existing investments in unmanaged code. Code that runs under the control of the common language runtime (CLR) is managed code, and code that runs outside the CLR is unmanaged code.

How to fetch data from excel sheet in C#? ›

The following code can be used to extract a row of data:
  1. var dataRow = worksheet. GetRow(1);
  2. var values = dataRow. Values;
  3. foreach (var value in values)
  4. {
  5. int intValue = (int)value;
  6. // Do something with the extracted value.
  7. }
Feb 26, 2023

Do you need Excel installed for Microsoft Office Interop Excel? ›

Yes, you are right. You need Excel to be installed to use the Excel Manipulation feature with Microsoft. Office. Interop.

How to read Excel file in C# Visual Studio Code? ›

How to Read Excel File in C#
  1. Download the C# Library to read Excel files.
  2. Load and read an Excel file (workbook)
  3. Create an Excel workbook in CSV or XLSX.
  4. Edit cell values in a range of cells.
  5. Validate spreadsheet data.
  6. Export data using Entity Framework.

Is Microsoft Office Interop Excel free or paid? ›

Office. Interop. Excel is free and it is giving error.

Can I use Microsoft Office Interop Outlook without Outlook installed? ›

It is not possible to use the Interop assemblies without its associated application installed where you need to use it. The Interop assemblies are used primarily as an advanced application automation system.

What is Microsoft Office Interop Excel? ›

Microsoft Office Interop (Excel Automation) is an option when creating/reading Excel files (XLS, XLSX, CSV) from C# or VB.NET application, but it has many drawbacks.

How does com interop work? ›

COM Interop is a technology included in the . NET Framework Common Language Runtime (CLR) that enables Component Object Model (COM) objects to interact with . NET objects, and vice versa. COM Interop aims to provide access to the existing COM components without requiring that the original component be modified.

How to access a collection in C#? ›

The Item property enables you to access an item in the elements collection by using the elements[symbol] in C#. The following example instead uses the TryGetValue method to quickly find an item by key.

How to reference a library in C#? ›

Write Code: In your C# code, add a using statement to reference the namespaces/classes from the library. For example: using MyLibraryNamespace; Build and Run: Build your console app and run it to test that the library is being used correctly.

How to send data from Excel to C#? ›

How to Export to Excel in C#
  1. Download the C# Library to Export Excel files.
  2. Write extension name while importing or exporting files.
  3. Export an Excel file using the .xls extension.
  4. Export .xlsx or .xls file to a .csv.
  5. Export .xlsx file data into .XML.
  6. Export .xlsx file data into .JSON.

How to read particular column values in Excel using C#? ›

DataTable dt = new DataTable(); foreach (Control checkbox in pnl. Controls) if (checkbox. GetType() == typeof(CheckBox) && ((CheckBox) checkbox).

How to read Excel file from local path in C#? ›

How to Read an Excel File in a C# Console Application
  1. Create a C# Console Application in Visual Studio.
  2. Install the IronXL C# Excel Library.
  3. Create a Workbook class Object.
  4. Load the Excel file using Workbook.Load method.
  5. Load the Worksheet using the WorkSheets method.
  6. Read the Excel File data using WorkSheet.Row method.
Apr 3, 2024

How to add Excel file in C#? ›

We will include sample code for each step to help you understand the process in detail.
  1. Step 1: Define the Document Directory. ...
  2. Step 2: Create a File Stream and Open the Excel File. ...
  3. Step 3: Instantiate a Workbook Object. ...
  4. Step 4: Add a New Sheet to the Workbook. ...
  5. Step 5: Set New Sheet Name. ...
  6. Step 6: Save the Excel File.

How to open an existing Excel file in C#? ›

Open an Existing Excel File in C#
  1. // Select worksheet at index 0.
  2. WorkSheet workSheet = workBook. WorkSheets [0];
  3. // Select worksheet by name.
  4. WorkSheet ws = wb. GetWorkSheet("Sheet1");
  5. // Get any existing worksheet.
  6. WorkSheet firstSheet = workBook. DefaultWorkSheet;
Jun 20, 2023

How to automate Microsoft Excel from Microsoft Visual C# net? ›

Create an Automation Client for Microsoft Excel
  1. Start Microsoft Visual Studio . ...
  2. On the File menu, click New, and then click Project. ...
  3. Add a reference to the Microsoft Excel Object Library. ...
  4. On the View menu, select Toolbox to display the toolbox, and then add a button to Form1.
  5. Double-click Button1.
Oct 21, 2021

Top Articles
How To Cook Omaha Steak Apple Tartlets
How to Cook Omaha Steak Apple Tartlets | The Ultimate Guide
AMC Theatre - Rent A Private Theatre (Up to 20 Guests) From $99+ (Select Theaters)
Junk Cars For Sale Craigslist
Midflorida Overnight Payoff Address
Txtvrfy Sheridan Wy
Craigslist Free Stuff Appleton Wisconsin
Trade Chart Dave Richard
Delectable Birthday Dyes
Poplar | Genus, Description, Major Species, & Facts
Mail Healthcare Uiowa
J Prince Steps Over Takeoff
Decaying Brackenhide Blanket
CSC error CS0006: Metadata file 'SonarAnalyzer.dll' could not be found
Whiskeytown Camera
Imbigswoo
Epaper Pudari
Bros Movie Wiki
Craigslist Alabama Montgomery
OSRS Dryness Calculator - GEGCalculators
Katherine Croan Ewald
Wicked Local Plymouth Police Log 2022
ARK: Survival Evolved Valguero Map Guide: Resource Locations, Bosses, & Dinos
Air Quality Index Endicott Ny
Village
Coomeet Premium Mod Apk For Pc
Bento - A link in bio, but rich and beautiful.
Bleacher Report Philadelphia Flyers
Cars & Trucks - By Owner near Kissimmee, FL - craigslist
SOGo Groupware - Rechenzentrum Universität Osnabrück
Times Narcos Lied To You About What Really Happened - Grunge
Craftybase Coupon
Cvs Sport Physicals
Miles City Montana Craigslist
Willys Pickup For Sale Craigslist
Craigslist Org Sf
Truckers Report Forums
Pill 44615 Orange
4083519708
Metro By T Mobile Sign In
Go Upstate Mugshots Gaffney Sc
Frcp 47
Google Chrome-webbrowser
Taylor University Baseball Roster
Xxn Abbreviation List 2023
manhattan cars & trucks - by owner - craigslist
Tricia Vacanti Obituary
Arnesons Webcam
Trending mods at Kenshi Nexus
Gonzalo Lira Net Worth
Marcel Boom X
Secondary Math 2 Module 3 Answers
Latest Posts
Article information

Author: Margart Wisoky

Last Updated:

Views: 5991

Rating: 4.8 / 5 (78 voted)

Reviews: 93% of readers found this page helpful

Author information

Name: Margart Wisoky

Birthday: 1993-05-13

Address: 2113 Abernathy Knoll, New Tamerafurt, CT 66893-2169

Phone: +25815234346805

Job: Central Developer

Hobby: Machining, Pottery, Rafting, Cosplaying, Jogging, Taekwondo, Scouting

Introduction: My name is Margart Wisoky, I am a gorgeous, shiny, successful, beautiful, adventurous, excited, pleasant person who loves writing and wants to share my knowledge and understanding with you.