使用代码从word文档的输入字段读取值

时间:2013-02-21 02:14:28

标签: c# ms-word

我在做这项工作时非常接近。基本上我想读取word文档中的输入字段。换句话说,我有:

enter image description here

Hello world 是我通过单击图像上突出显示的 Aa 按钮放置的标签的内容。因此,当我将该文档保存为Test.docx时,我会使用以下代码执行以下操作:

using System;
using Microsoft.Office.Interop.Word;

class Program
{
    static void Main(string[] args)
    {
        Application word = new ApplicationClass();
        object miss = System.Reflection.Missing.Value;
        object path = @"a:\Users\Eduardo\Desktop\Test.docx";  // <-------- Path where document is
        object readOnly = false;
        Document document = word.Documents.Open(ref path, ref miss, ref readOnly, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss);

        // here I iterate through all the input fields!!!  <--------------------------
        foreach (ContentControl ff in document.ContentControls)
        {
            var m = ff.PlaceholderText; // for some reason I cannot get the text of the control.
            var b = ff.ShowingPlaceholderText;
            Console.WriteLine(ff.ToString());
        }

        document.Close(ref miss, ref miss, ref miss);
        word.Quit();
    }
}

我能够遍历所有输入字段,我唯一想做的就是获取控件内的值!


修改

终于找到了解决方案由于某种原因,该属性没有出现在调试器上!无论如何要获得我必须做的控制文本:

 Console.WriteLine(ff.Range.Text);

所以我的finall代码现在看起来像:

using System;
using Microsoft.Office.Interop.Word;

class Program
{
    static void Main(string[] args)
    {
        Application word = new ApplicationClass();
        object miss = System.Reflection.Missing.Value;
        object path = @"a:\Users\Eduardo\Desktop\Test.docx";  // <-------- Path where document is
        object readOnly = false;
        Document document = word.Documents.Open(ref path, ref miss, ref readOnly, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss);

        foreach (ContentControl ff in document.ContentControls)
        {
            Console.WriteLine(ff.Range.Text);
        }

        document.Close(ref miss, ref miss, ref miss);
        word.Quit();
    }
}

0 个答案:

没有答案