使用 Word Interop 卡在嵌套 table 的 Word 文档中

stuck in nested table in a word document using Word Interop

while (doc.ActiveWindow.Selection.Bookmarks.Exists(@"\EndOfDoc") == false)
                {
                    //Skiping table content and proceeding with only paragraphs  
                    if (doc.ActiveWindow.Selection.get_Information(WdInformation.wdWithInTable) == false)
                    {
                        doc.ActiveWindow.Selection.EndKey(ref wdLine, ref wdExtend);
                        currLine = doc.ActiveWindow.Selection.Text;
                        temp = currLine;
                        // Move to next line after assigning to temp
                        doc.ActiveWindow.Selection.MoveDown(ref wdLine, ref wdCountOne, ref wdMove);
                        doc.ActiveWindow.Selection.HomeKey(ref wdLine, ref wdMove);
                        //<Match some text on paragraph>
                            if (temp.StartsWith(searchValue))
                            {
                                resultValue = temp;
                                 break;
                            }  
                    }
                    else //If its a table
                    {
                        // navigate to next line
                        while (doc.ActiveWindow.Selection.get_Information(WdInformation.wdWithInTable) == true)
                        {
                            if (doc.ActiveWindow.Selection.Bookmarks.Exists(@"\EndOfDoc"))
                            break;
                            doc.ActiveWindow.Selection.MoveDown(ref wdLine, ref wdCountOne, ref wdMove);
                            doc.ActiveWindow.Selection.HomeKey(ref wdLine, ref wdMove);
                        }
                            doc.ActiveWindow.Selection.MoveDown(ref wdLine, ref wdCountOne, ref wdMove);
                            doc.ActiveWindow.Selection.HomeKey(ref wdLine, ref wdMove);
                        }
                }

我是 C# 的新手,我正在尝试使用 Interop 通读 word 文档,在这样做时,我被困在文档中存在的嵌套 table 中,并且控件一直围绕着这个 table无限期。这里的问题似乎是它无法从 table 中出来,因此无法找到“\EndOfDoc”书签。非常感谢任何有关退出 table 和进行进一步处理的帮助。

您可以为 Table 对象创建一个范围,然后将该范围折叠到其终点以超出 table 这将替换第二个 while 循环:

 Word.Range rngTable = null;
 object oCollapseEnd = WdCollapseDirection.wdCollapseEnd;
 if (doc.ActiveWindow.Selection.get_Information(WdInformation.wdWithinTable) == true)
 {
    rngTable = doc.ActiveWindow.Selection.Tables[1].Range;
    rngTable.Collapse(ref oCollapseEnd);
    rng.Select();
  }

注意 1:我在脑海中打字是因为我不在可以测试它的机器上,所以请注意小的语法错误...

注意 2:您可能想尝试声明一个 Selection 对象,而不是使用 doc.ActiveWindow...,因为它更容易阅读、更容易键入并且可能更有效地执行:

 Word.Selection sel = doc.ActiveWindow.Selection

注意 3:通常,您根本不应该使用选择,而应该使用范围。但是,如果您想逐行工作,您真的没有太多选择。但是,如果这些行实际上是段落(末尾有回车 return),那么有一种更高效、更简洁的方法来编写您所拥有的内容。