如何使用 c#.net 读取 MS word 表单字段
How to read MS word form fields using c#.net
我尝试阅读包含文本和表单字段的 word 文档。我需要阅读文档中的所有文本和字段。但是下面的代码总是 return 空值。它永远不会进入 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 shape in doc.InlineShapes)
{
if (shape.OLEFormat != null && shape.OLEFormat.ClassType == "CONTROL Forms.TextBox.1")
{
Console.WriteLine("Data :" + shape.OLEFormat.Object.Value);
}
}
我尝试阅读包含文本和表单字段的 word 文档。我需要阅读文档中的所有文本和字段。但是下面的代码总是 return 空值。它永远不会进入 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 shape in doc.InlineShapes)
{
if (shape.OLEFormat != null && shape.OLEFormat.ClassType == "CONTROL Forms.TextBox.1")
{
Console.WriteLine("Data :" + shape.OLEFormat.Object.Value);
}
}