如何使用c#.net读取MS单词表单字段

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

我试着阅读包含文本和表单字段的word文档。我需要阅读文档中的所有文本和字段。但是下面的代码总是返回空值。它永远不会进入foreach循环。由于构建时没有错误,我不知道是什么问题。但我没有得到输出。我在c#.net 4.6.2中编写它,它将用作库文件。代码有什么问题吗?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Office.Interop.Word;
using System.Activities;
using System.ComponentModel;
namespace WordExer
{
  public class WordExer : CodeActivity
  {
    [Category("Input")]
    public InArgument<string> AVal { get; set; }

    [Category("Output")]
    public OutArgument<string> CVal { get; set; }

    protected override void Execute(CodeActivityContext context)
    {
        var a = AVal.Get(context);
        string text = "";
         Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
        Microsoft.Office.Interop.Word.Document doc = word.Documents.Add(a);

        doc.Activate();

        foreach (FormField field in doc.FormFields)
        {
            Console.WriteLine(field.Range.Text);
            text += field.Range.Text;
        }
        CVal.Set(context, text);
        word.Quit();
    }  
  }
}
c# .net ms-word office-interop
1个回答
1
投票

您可以尝试以内嵌形状的形式访问它们,如下面的代码段所示

 foreach (InlineShape shape in doc.InlineShapes)
 {
       if (shape.OLEFormat != null && shape.OLEFormat.ClassType == "CONTROL Forms.TextBox.1")
       {
              Console.WriteLine("Data :" + shape.OLEFormat.Object.Value);
       }
 }
© www.soinside.com 2019 - 2024. All rights reserved.