简体   繁体   中英

"Cannot load file or assembly" - Microsoft.Office.Interop.Excel

I have a project targeting.Net 6.0 framework and I am trying to use Microsoft.Office.Interop.Excel as I would like to run an excel macro configured inside the.xlsm file that exists on the same local system. Regarding Excel version - I am running Microsoft 365 (I am not sure how this translates into Excel versions that used to be more explicit in the naming earlier). The error that I have when running my code is shown here:
1个

This is the code where the problem occurs (last line basically):

void RunMacro(string macroFilename)
{
    Excel.Application xlApp = new Excel.Application();
    Excel.Workbook xlWorkBook;
   
    xlWorkBook = xlApp.Workbooks.Open(macroFilename);
    xlApp.Visible = true;

    xlApp.Run("Main");
}

For including Interop.Excel package in the project, I tried to install it as a NuGet package, so in that case the project file looks like this

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net6.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="DotNetCore.NPOI" Version="1.2.3" />
    <PackageReference Include="ExcelDataReader" Version="3.6.0" />
    <PackageReference Include="ExcelDataReader.DataSet" Version="3.6.0" />
    <PackageReference Include="Microsoft.Office.Interop.Excel" Version="15.0.4795.1001" />
  </ItemGroup>

</Project>

Alternatively, I tried to refer to the interop dll using the "Add project reference" option, so here is how the project file looks in that case:

 <Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net6.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="DotNetCore.NPOI" Version="1.2.3" />
    <PackageReference Include="ExcelDataReader" Version="3.6.0" />
    <PackageReference Include="ExcelDataReader.DataSet" Version="3.6.0" />
  </ItemGroup>

  <ItemGroup>
    <Reference Include="Microsoft.Office.Interop.Excel">
      <HintPath>..\..\..\..\..\..\Windows\assembly\GAC_MSIL\Microsoft.Office.Interop.Excel\15.0.0.0__71e9bce111e9429c\Microsoft.Office.Interop.Excel.dll</HintPath>
    </Reference>
  </ItemGroup>

</Project>

However, in the end, the error from the screenshot remains in both cases. What could be causing this? Thanks a lot for any help.

You need to have corresponding version of Office installed. It means for Interop version 15.0.0.0 you should have Office 2013 and other versions of Office will not work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM