我可以在 Office365 中使用 WordInterop 功能吗?

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

我必须重构非常旧的代码(2005 年之前)。软件应打开 Word 文档并用数据填充标题中的变量。文档将打开,但变量为空。 我使用以下代码来显示 Word 文档中的 var 数量以进行一些测试。 它总是说有 0...我可以在 Office 365 中使用 WordInterop 吗?

using Microsoft.Office.Interop.Word;

namespace CheckForVariablesInWord
{
    class Program
    {
        static void Main(string[] args)
        {           
            Microsoft.Office.Interop.Word.Application ap = new Microsoft.Office.Interop.Word.Application();
            Document document = ap.Documents.Open(@"C:\temp\TestDocument.docx");
            ap.Visible = true;
            System.Console.WriteLine(document.Variables.Count);
            System.Console.ReadLine();
        }
    }
}

这是 TestWordDocument:

这是名为“myTest”的变量

{ 文档变量 myTest * 合并格式}

谢谢如果有人能在我生病之前帮助我;.)

c# office365 office-interop
1个回答
0
投票

你可以! 您可能需要在 Visual Studio 安装程序中安装 Office/Sharepoint 开发工作负载

您需要将 Word 的 COM 引用添加到 .csproj 文件中:

<ItemGroup>
  <COMReference Include="Microsoft.Office.Interop.Word">
    <WrapperTool>tlbimp</WrapperTool>
    <VersionMinor>7</VersionMinor>
    <VersionMajor>8</VersionMajor>
    <Guid>00020905-0000-0000-c000-000000000046</Guid>
    <Lcid>0</Lcid>
    <Isolated>false</Isolated>
    <EmbedInteropTypes>true</EmbedInteropTypes>
  </COMReference>
</ItemGroup>

通过 Visual Studio UI 执行此操作可能更容易,方法是右键单击项目的

dependencies
,然后单击
add COM reference...
,然后选择
Microsoft Word 16.0 Object Library
。这同样适用于 Excel - 只需确保勾选
Microsoft Excel 16.0 Object Library

如果这不起作用,请卸载 NuGet 包并重试。

希望这有帮助!

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