【发布时间】: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