如何使用 Word Interop 获取 Word 文档中特定单词的范围

How to get the range of a specific word in Word Document using Word Interop

我正在创建一个在 word 文档中插入 table 的 C# 程序。现在,我需要在不同的word文档的某个位置插入一个table。我拥有的所有单词 documents/templates 中都有单词 <table>,我想在其中插入 table。为了能够在那个特定的 word 文档位置插入 table,我需要获取单词 <table> 的位置范围。有什么可能的方法来获取单词文档中特定单词的范围吗?

我在搜索过的参考资料中看到的都是使用 space、单词、句子等的计数来获取范围,例如:

object start = doc.Words[2].Start; //start of the second word
object end = doc.Words[2].End; // start of the third word

Word.Range myRange = doc.Range(ref start, ref end);

由于我的word文档中的字数是动态的,上面的代码不是很有帮助。

有没有什么方法可以使用 C# word interop 获取 word 文档中特定单词的范围?

您可以使用空(或任何)RangeFind 对象将范围的边界设置为文档中的特定 word/string:

Word.Range range = document.Range(0, 0);
if (range.Find.Execute("<table>")) {
    // range is now set to bounds of the word "<table>"
}

Execute 方法有额外的参数(用于执行不区分大小写的匹配等)。