Search code examples
c#excel.net-corecom

.net core COM with Excel range


I have an issue where I am unable to access the Name object of a range. So, I am calling Excel.Application.get_Range() and passing in a name. It returns a non-null object and I can access methods. However, Range.Name returns a System.__ComObject(). If I try to access Range.Name.Name I get an exception similar to the following

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: ''System.__ComObject' does not contain a definition for "Name"

Also, this project is one that I migrated from .net Framework to .net Core. The exact same code works in Framework. I have tried various methods of trying to determine what the underlying type is (because it does not appear to be a Name object). ITypeInfo returns that the typename is Name so it does appear to be a name object.

I'm at a loss as to why I'm unable to access Name.Name in .net core. When I check the .net Core Excel sample they never access a name object.

Also, I am able to access other COM objects like ListObject just fine.


Solution

  • I figured out what the issue is. For anyone else running into this with .net Core, the problem is that .net core appears to not support dynamic types through COM automatically. This is discussed in the following github issue Github issue about dynamic not working. Where it talks about why this doesn't work.

    Basically, for my specific case I needed to cast the type manually and then it worked. This also impacts use of IEnumerable COM types needing to be cast directly to IEnumerable before iterating through them.

    Assuming you have the following using statement.

    using Excel = Microsoft.Office.Interop.Excel;
    

    I had to turn the following:

    return range.Name.Name;
    

    into

    return ((Excel.Name)range.Name).Name;
    

    As an aside, I also noticed that if you copy/paste the cast above into the debug watch window it does not display properly and instead shows an exception about an invalid cast.