PowerPoint.Application.Presentations 缺少 MsoTriState

Rem*_*_rm 6 c# powerpoint reference

我正在尝试使用 C# 中的 PowerPoint 来自动化流程,为此我想打开(或创建新的)PowerPoint 演示文稿,添加幻灯片并保存文档。

我已在我的计算机上安装了整个 Office 2019 软件包,并且可以通过引用Interop.Microsoft.Office.Interop.PowerPoint(来自 Microsoft PowerPoint 16.0 对象库参考)以及Interop.Microsoft.Office.Core(来自 Microsoft Office 16.0 对象库参考)来访问 ppt api。

我尝试使用以下代码打开一个powerpoint:

using Microsoft.Office.Interop.PowerPoint;
using Microsoft.Office.Core;

class PowerPointManager
{
    public PowerPointManager()
    {
        string powerPointFileName = @"C:\temp\test.pptx";

        Application pptApplication = new Application();
        Presentation ppt = pptApplication.Presentations.Open(powerPointFileName, MsoTriState.msoTrue); //MsoTriState comes from Microsoft.Office.Core

    }
}

Run Code Online (Sandbox Code Playgroud)

然而,这会导致线路出现错误pptApplication.Presentations.Open

错误 CS0012 类型“MsoTriState”是在未引用的程序集中定义的。您必须添加对程序集“office,Version=15.0.0.0,Culture=neutral,PublicKeyToken=71e9bce111e9429c”的引用

即使MsoTriState是最明确定义的,Microsoft.Office.Core它是程序集的一部分office.dllmsdn参考

当我尝试使用 VS2019 的快速操作时,我得到“添加对“office 版本 15.0.0.0”的引用”的选项。执行此快速操作将打开引用管理器,但不会添加任何引用。手动搜索“Office”也不会产生任何简单命名为“office”的结果。最接近的是“Microsoft Office 16.0 Object Library”,已被引用。

据我所知,这与函数参数要求的 MsoTriStrate 相同,那么为什么它不接受这个呢?尝试用 MsoTriState 值替换其整数值(例如 -1 表示 true)也不起作用。

使用 .NET Core 3.1 WinForms、Office 2019(包括 powerpoint)32 位、W10 x64 企业版和安装了 Office/Sharepoint 开发工具集的 Visual Studio 2019。

Ann*_*ina 2

看起来互操作程序集tlbimp在某个时刻生成不正确。您可以在 找到该程序集\obj\Debug\netcoreapp3.1\Interop.Microsoft.Office.Interop.PowerPoint.dll

要正确重新生成它,您需要执行以下操作:

  1. 删除对“Microsoft PowerPoint 16.0 对象库”的引用。清理并重建项目。此时,您还可以尝试卸载项目并手动删除bin和文件夹。obj
  2. 添加对“Microsoft 15.0 对象库”和“Microsoft 16.0 对象库”的引用。
  3. 添加对“Microsoft PowerPoint 16.0 对象库”的反向引用,并再次清理和重建项目。

执行这些步骤后,我的.NET Core 3.1 WinForms项目已成功编译。

以下是我的案例中文件的内容.csproj

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

  <PropertyGroup>
    <OutputType>WinExe</OutputType>
    <TargetFramework>netcoreapp3.1</TargetFramework>
    <UseWindowsForms>true</UseWindowsForms>
  </PropertyGroup>

  <ItemGroup>
    <COMReference Include="Microsoft.Office.Core">
      <WrapperTool>tlbimp</WrapperTool>
      <VersionMinor>8</VersionMinor>
      <VersionMajor>2</VersionMajor>
      <Guid>2df8d04c-5bfa-101b-bde5-00aa0044de52</Guid>
      <Lcid>0</Lcid>
      <Isolated>false</Isolated>
      <EmbedInteropTypes>true</EmbedInteropTypes>
    </COMReference>
    <COMReference Include="Microsoft.Office.Interop.PowerPoint">
      <WrapperTool>tlbimp</WrapperTool>
      <VersionMinor>12</VersionMinor>
      <VersionMajor>2</VersionMajor>
      <Guid>91493440-5a91-11cf-8700-00aa0060263b</Guid>
      <Lcid>0</Lcid>
      <Isolated>false</Isolated>
      <EmbedInteropTypes>true</EmbedInteropTypes>
    </COMReference>
  </ItemGroup>

</Project>
Run Code Online (Sandbox Code Playgroud)