Console app referencing excel interop RCW

Magne 126 Reputation points
2024-05-15T21:34:05.65+00:00

Using VS2022 and Net 8 to make a console app referencing excel interop RCW.

On my development machine this interop file is version 16 (MS 365) and works just fine, however on another machine with same OS, same dotnet runtime (runtime shouldn't matter as long as I publish self-contained), but Office 2010 (which is version 14?) it does not work.

I am pretty sure this has to do with the office version on the target machine, but I don't know how to develop against an older interop.
Note that this sample case (real app is way more complex) is a console app and VSTO is not relevant.

Anyone knows the right way to go? (and of course it must work on machine with office 2013, 2016,2019 and whatever newer including the 365)

My little program is this simple:

using Microsoft.Office.Interop.Excel;

using System;

using System.IO;

Application excelApp = new();

string path = Directory.GetCurrentDirectory();

Workbook workbook = excelApp.Workbooks.Open(Path.Combine(path, "Testbook.xlsx"));

foreach (Worksheet ws in workbook.Worksheets)

{

Console.WriteLine(ws.Name);

}

Error is invalid cast exception on line 4 (new'ing excelApp)

Excel
Excel
A family of Microsoft spreadsheet software with tools for analyzing, charting, and communicating data.
1,547 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,404 questions
Office Development
Office Development
Office: A suite of Microsoft productivity software that supports common business tasks, including word processing, email, presentations, and data management and analysis.Development: The process of researching, productizing, and refining new or existing technologies.
3,594 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. KOZ6.0 5,375 Reputation points
    2024-05-16T00:31:07.27+00:00

    If you don't want to depend on the Excel version, use late binding.

    Type excelType = Type.GetTypeFromProgID("Excel.Application");
    dynamic excelApp = Activator.CreateInstance(excelType);
    string path = Directory.GetCurrentDirectory();
    dynamic workbook = excelApp.Workbooks.Open(Path.Combine(path, "Testbook.xlsx"));
        ・
        ・
    

    Or how about getting the source of NetOfficeFw.Excel and compiling it for use with NET8?
    https://github.com/NetOfficeFw/NetOffice