我有代码(如下所示)循环遍历所有段落并找到一个特定的字符串。当我找到字符串时,我打印出它所属的标题的自动编号。问题是,我也想要标题号,但无法弄清楚如何获取它。代码在这里:
修改:使用工作内容清理代码
string LastHeader = "";
foreach (Paragraph paragraph in aDoc.Paragraphs)
{
Microsoft.Office.Interop.Word.Style thisStyle =
(paragraph.Range.get_Style() as Microsoft.Office.Interop.Word.Style);
if (thisStyle != null && thisStyle.NameLocal.StartsWith("Heading 2"))
{
LastHeader = paragraph.Range.ListFormat.ListString + " " +
paragraph.Range.Text.Replace("\"", "\"\"").Replace("\r", "");
}
else
{
string content = paragraph.Range.Text;
for (int i = 0; i < textToSearch.Count; i++)
{
if (content.Contains(textToSearch[i]))
{
// Do stuff here
}
}
}
}
答案 0 :(得分:3)
每当我重新阅读您的信息时,我都会感觉我并不完全理解您所要求的内容,因此以下内容可能包含的信息比您正在寻找的内容更多...... < / p>
获取特定段落的编号:
paragraph.Range.ListFormat.ListString
Word有一些内置的书签,可以为您提供其他很多工作要确定的信息。其中一个是\ HeadingLevel。这将获得第一段格式,其中标题样式位于SELECTION之前。这是一个棘手的部分,因为我们并不真的想做出选择......但它可以追溯到旧的WordBasic时代代码模仿用户行为,所以我们一直坚持这个
textToAnalyse.Select
aDoc.Bookmarks("\HeadingLevel").Range.ListFormat.ListString
书签调用本身不会改变选择。
我看到的另一个选项,因为你已经循环了Paragraphs集合,将检查paragraph.Range.Style,如果它以字符串&#34; Heading&#34;开头。 (假设在这些文档和样式中没有使用它们)保存ListFormat.ListString
,以便在满足条件时可以调用它。