【问题标题】:How to read MS word form fields using c#.net如何使用 c#.net 读取 MS Word 表单字段
【发布时间】:2019-04-26 13:35:22
【问题描述】:

我尝试阅读包含文本和表单字段的 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();
    }  
  }
}

【问题讨论】:

  • 你可以试试 foreach(InlineShape filed in doc.InlineShapes) --->这会遍历你文档中的所有字段
  • @ApoorvaRaju 我认为形状和表单控件是不同的。我尝试了形状。它适用于文本框,但不适用于表单输入控件。
  • 您确定这些是表单字段,而不是其他内容,例如内容控件吗?如果你 Debug.Print doc.FormFields.Count,返回什么?如果您不确定这些输入字段是什么,使用什么命令来插入它们?也许提供一个屏幕截图...
  • @ApoorvaRaju InlineShapes 有效,但 field.Range.Text 仅返回 "CONTROL Forms.TextBox.1"。我想获得每个的价值。
  • @Cindy FormFields.Count 什么也不返回。这些字段是 ActiveX 控件

标签: c# .net ms-word office-interop


【解决方案1】:

您可以尝试将它们作为内联形状访问,如下面的代码 sn-p 所示

 foreach (InlineShape shape in doc.InlineShapes)
 {
       if (shape.OLEFormat != null && shape.OLEFormat.ClassType == "CONTROL Forms.TextBox.1")
       {
              Console.WriteLine("Data :" + shape.OLEFormat.Object.Value);
       }
 }

【讨论】:

  • 谢谢@Apoorva。有用。我将 if 条件行 修改为if (shape.OLEFormat != null &amp;&amp; shape.OLEFormat.ClassType == "Forms.TextBox.1")。我想编辑word文档也会这样。
  • 欢迎 :) 是的,您可以编辑 object.value 来编辑 word 文件并稍后保存
  • 有没有办法根据索引获取价值?像这样的 doc.InlineShapes[1].OLEFormat.Object.Value.
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-09-09
  • 2010-12-08
  • 1970-01-01
  • 2012-05-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多