无法使用 Microsoft.Office.Interop.Excel 加载文件或程序集“office,版本 = 15.0.0.0”

Tra*_*Son 2 .net c# excel office-interop

我正在使用Microsoft.Office.Interop.Excel将excel转换为pdf。但是当我启动 Excel 应用程序时,发生了这个错误。我已经在我的电脑上安装了Excel 2013。(我使用的是 VS2019,Window 10)。

我的 Excel 的位置在C\Program Files (x86)\Microsoft Office\Office 15\Excel.

无法加载文件或程序集“office,版本=15.0.0.0,文化=中性,PublicKeyToken=xxxxxxxxxxx”。该系统找不到指定的文件

欢迎任何建议!

这是我的代码:

using Microsoft.Office.Interop.Excel;
using System;
using System.Runtime.InteropServices;

namespace ExcelToPdf
{
    public class ExcelApplicationWrapper : IDisposable
    {
        public Application ExcelApplication { get; }

        public ExcelApplicationWrapper()
        {
            ExcelApplication = new Application(); // start excel application
        }

        public void Dispose()
        {
            // Each file I open is locked by the background EXCEL.exe until it is quitted
            ExcelApplication.Quit();
            Marshal.ReleaseComObject(ExcelApplication);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;

namespace ExcelToPdf
{
    public class ExcelInteropExcelToPdfConverter
    {
        public void ConvertToPdf(IEnumerable<string> excelFilesPathToConvert)
        {
            using (var excelApplication = new ExcelApplicationWrapper()) // got error here
            {

            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

小智 5

这是答案https://github.com/dotnet/project-system/issues/5735

为了解决这个问题,项目系统需要添加True。

老的:

<ItemGroup>
    <COMReference Include="Microsoft.Office.Excel.dll">
        <Guid>00020813-0000-0000-c000-000000000046</Guid>
        <VersionMajor>1</VersionMajor>
        <VersionMinor>7</VersionMinor>
        <WrapperTool>tlbimp</WrapperTool>
        <Lcid>0</Lcid>
        <Isolated>false</Isolated>
    </COMReference>
</ItemGroup>
Run Code Online (Sandbox Code Playgroud)

新的:

<ItemGroup>
    <COMReference Include="Microsoft.Office.Interop.Excel">
        <Guid>{00020813-0000-0000-C000-000000000046}</Guid>
        <VersionMajor>1</VersionMajor>
        <VersionMinor>7</VersionMinor>
        <Lcid>0</Lcid>
        <WrapperTool>primary</WrapperTool>
        <Isolated>False</Isolated>
        <EmbedInteropTypes>True</EmbedInteropTypes>
    </COMReference>
</ItemGroup>
Run Code Online (Sandbox Code Playgroud)