使用 COM 时 Excel 加载项中的回调静默失败

问题描述 投票:0回答:2

使用 Visual Studio 2022 和 Excel 365...

我已经能够使用 ExcelDna 完成大量任务。当我尝试直接使用 Excel COM 接口时遇到了麻烦。

首先,我在自定义 UI XML 中定义一个按钮:

<button id='button_sample' label='Sample' onAction='OnSample' />

这个简单的功能有效:

public void OnSample(IRibbonControl control)
{
    Debug.WriteLine("Starting sample...");
}

现在我想扩展这个功能来了解用户的选择:

public void OnSample(IRibbonControl control)
{
    Debug.WriteLine("Starting sample...");
    try
    {
        Excel.Application app = (Excel.Application)ExcelDnaUtil.Application;
        Excel.Range range = (Excel.Range)app.Selection;
        object[,] values = (object[,])range.Value2;
        Debug.WriteLine($"Length: {values.Length}");
    }
    catch (Exception ex)
    {
        MessageBox.Show($"Exception: {ex.Message}");
    }
}

我需要添加 interop 程序集。但是,以下行:

using Excel = Microsoft.Office.Interop.Excel;

收到此错误:

The type or namespace name 'Office' does not exist in the namespace 'Microsoft' (are you missing an assembly reference?)    

在“解决方案资源管理器”窗格中,我可以右键单击“依赖项”并选择“添加 COM 引用...”。我搜索“excel”并看到“Microsoft Excel 16.0 对象库”。我启用此功能并点击“确定”。

现在构建出现了新错误:

Could not determine the dependencies of the COM reference "Microsoft.Office.Interop.Excel". Error loading type library/DLL. (Exception from HRESULT: 0x80029C4A (TYPE_E_CANTLOADLIBRARY))   

如果我右键单击程序集并选择“打开包含文件夹”,结果就是我的项目目录。集会不可能在那里!

因此我删除了该程序集并返回到“添加 COM 引用...”。这次我点击“浏览...”并找到旧版本:

C:\Windows\assembly\GAC_MSIL\Microsoft.Office.Interop.Excel\15.0.0.0__71e9bce111e9429c\Microsoft.Office.Interop.Excel.dll

不再出现构建错误,但我的

OnSample()
函数无法运行。没有调试输出或异常;这只是无声的失败。

这就是我现在的处境。


好吧,我尝试过其他一些事情:

  • 在我的
    .csproj
    文件中参考NuGet最新版本:

<PackageReference Include="MSOffice.Interop" Version="16.*" />

出现错误:

Package 'MSOffice.Interop 16.0.55555' was restored using '.NETFramework,Version=v4.6.1, .NETFramework,Version=v4.6.2, .NETFramework,Version=v4.7, .NETFramework,Version=v4.7.1, .NETFramework,Version=v4.7.2, .NETFramework,Version=v4.8, .NETFramework,Version=v4.8.1' instead of the project target framework 'net6.0-windows7.0'. This package may not be fully compatible with your project.

无声的失败仍在继续。

  • 安装 Visual Studio 的 VSTO:

转到控制面板 -> 程序和功能。右键单击“Visual Studio Community 2022”并选择“修改”。在顶部栏中选择“单个组件”并搜索“VSTO”。

但这对解决上面的“Microsoft Excel 16.0 对象库”错误没有帮助。

c# excel-addins excel-dna
2个回答
0
投票

原来我只需要通过添加到我的 .csproj 文件来

使用 ExcelDna.Interop

<PackageReference Include="ExcelDna.Interop" Version="*" />

0
投票

ExcelDna.Interop 库目前仅适用于 Office 13 的版本 15,该版本已不再支持,因此我认为这不是一个好的解决方案。但是,当我想添加对象库作为绝对引用时,我也找不到另一个。

© www.soinside.com 2019 - 2024. All rights reserved.