无法使用Microsoft.Office.Interop.Excel加载文件或程序集的办公室,版本= 15.0.0.0

时间:2019-11-27 09:34:33

标签: c# .net 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

  

无法加载文件或程序集“办公室,版本= 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);
        }
    }
}
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
            {

            }
        }
    }
}

1 个答案:

答案 0 :(得分:2)

这是答案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>

新功能:

<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>