我想使用 Microsoft Office 互操作 Word 程序集来阅读 word 文档的页眉和页脚。
我有两个问题:
首先如何访问脚注和标题?其次如何将它们转换为字符串(当我调用 toString() 时我刚刚得到“System.__ComObject”)
您应该有一个由许多部分组成的 Document 对象文档,并且页脚/页眉是单个部分的一部分。每个部分可以有多个页眉/页脚(例如,第一页的页眉/页脚可能不同)。要访问页眉/页脚的文本,您必须获取页眉/页脚中包含的 Range,然后访问其 Text 属性。
如果 app 是您的 Word ApplicationClass,则此代码应为您提供两个包含活动文档的页眉和页脚的集合:
List<string> headers = new List<string>();
List<string> footers = new List<string>();
foreach (Section aSection in app.ActiveDocument.Sections)
{
foreach (HeaderFooter aHeader in aSection.Headers)
headers.Add(aHeader.Range.Text);
foreach (HeaderFooter aFooter in aSection.Footers)
footers.Add(aFooter.Range.Text);
}
如果您对脚注而不是页脚感兴趣(从问题中并不清楚,因为您在某些地方写了脚注,而在其他地方写了页脚),事情就更简单了,因为您可以向文档询问所有脚注的集合。要访问注释中的文本,您可以对页眉/页脚执行相同的操作:访问 Range,然后获取 Text 属性:
List<string> footNotes = new List<string>();
foreach (Footnote aNote in app.ActiveDocument.Footnotes)
footNotes.Add(aNote.Range.Text);