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

3

我正在使用 Microsoft.Office.Interop.Excel 将 Excel 转换为 PDF。但是当我启动 Excel 应用程序时,会出现以下错误。我已经在计算机上安装了 Excel 2013。 (我正在使用 VS2019,Windows 10)。

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

无法加载文件或程序集“office,Version=15.0.0.0,Culture=neutral,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
            {

            }
        }
    }
}

没有必要调用 Marshal.ReleaseComObject - user585968
1
我不认为问题来自于 Dispose() 函数。我只是调用了 ExcelApplication = new Application(); - Tran B. V. Son
安装的Interop版本必须与正在使用的Excel版本匹配。您是否尝试在运行应用程序之前至少打开过一次Excel 2013?第一次打开Excel时,属性会在Windows中设置。Interop安装在c:\ Program File文件夹中,但找不到15版(Excel 2013)的Interop。 - jdweng
https://dev59.com/4WEi5IYBdhLWcg3wueN0#21018418 - Hans Passant
@TranB.V.Son 你能否克隆这个仓库 https://github.com/FrancescoBonizzi/Xls2Pdf,构建并运行它,并告诉我是否遇到了同样的问题? - Francesco Bonizzi
显示剩余4条评论
1个回答

6

以下是答案: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>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接