如何选择ms字搜索标签的单词

时间:2014-08-26 06:57:46

标签: c# search ms-word

我有一个word文档,我从c#代码打开(参见下面的代码)。单词文档可以包含单词文档可以包含的任何内容(表格,图片和任何内容)。 有关该文件的足够信息。我想要的是搜索特定标记,然后选择整个单词。

实施例

这可能是我想要找到的单词之前的文字, !#Command1这可能是我想要找到的单词之后的文本 !#Command2可能是这里的照片还是其他东西 !#指令代码

我想选择3个单词(!#Command1,!#Command2,!#Command3)并将它们添加到列表中。

CODE:

        public List<string> getListOfCommands()
        {
            List<string> commandList = new List<string>();
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.ShowDialog();
            object fileName = ofd.FileName;

            Word.Application wapp = GetWordApp();
            var document = wapp.Documents.Open(fileName);

            object findText = "!#"; //Commands tag
            wapp.Selection.Find.ClearFormatting();
            if(wapp.Selection.Find.Execute(findText))
            {
                //Add the !#Command to a list here
            }
            else
            {

            }
            return commandList;
        }

1 个答案:

答案 0 :(得分:0)

我花了一些时间在上面,并通过addind和endTag找到问题的解决方法。

新代码:

public List<string> getListOfCommands()
        {
            List<string> commandList = new List<string>();

            OpenFileDialog ofd = new OpenFileDialog();
            ofd.ShowDialog();
            object fileName = ofd.FileName;

            Word.Application wapp = GetWordApp();
            var document = wapp.Documents.Open(fileName);
            var range1 = document.Range();
            var range2 = document.Range();

            string findTextStart = "!#"; //Commands tagStart
            string findTextEnd = "#!"; //Commands tagEnd
            wapp.Selection.Find.ClearFormatting();

            range1.Find.Execute(findTextStart);
            while (range1.Find.Found)
            {
                if (range1.Text.Contains(findTextStart))
                {
                    range2.Find.Execute(findTextEnd);
                    if (range1.End < range2.Start)
                    {
                        Word.Range temprange = document.Range(range1.End, range2.Start);
                        commandList.Add(temprange.Text);
                    }
                    else
                    {
                        commandList.Add("Error - Are you missing a start or end tag?");
                    }
                }
                range1.Find.Execute(findTextStart);
            }
            return commandList;
        }