OpenXml Word Footnotes



我正在尝试迭代Word文档并从中提取脚注,并参考它们属于段落的位置。
我不知道该怎么做。

我看到,为了获得所有的脚注,我可以这样做:

FootnotesPart footnotesPart = doc.MainDocumentPart.FootnotesPart;
if (footnotesPart != null)
{
    IEnumerable<Footnote> footnotes = footnotesPart.Footnotes.Elements<Footnote>();
    foreach (var footnote in footnotes)
    {
         ...
    }
}

然而,我不知道如何知道每个脚注在段落中的位置。
例如,我想取一个脚注,并将它放在文本内的括号中,它之前是一个脚注。
我该怎么做呢?

必须找到与FootNote具有相同Id的FootnoteReference元素。这将为您提供Run元素,即脚注所在位置。

示例代码:

FootnotesPart footnotesPart = doc.MainDocumentPart.FootnotesPart;
if (footnotesPart != null)
{
    var footnotes = footnotesPart.Footnotes.Elements<Footnote>();
    var references = doc.MainDocumentPart.Document.Body.Descendants<FootnoteReference>().ToArray();
    foreach (var footnote in footnotes)
    {
        long id = footnote.Id;
        var reference = references.Where(fr => (long)fr.Id == id).FirstOrDefault();
        if (reference != null)
        {
            Run run = reference.Parent as Run;
            reference.Remove();
            var fnText = string.Join("", footnote.Descendants<Run>().SelectMany(r => r.Elements<Text>()).Select(t => t.Text)).Trim();
            run.Parent.InsertAfter(new Run(new Text("(" + fnText + ")")), run);
        }
    }
}
doc.MainDocumentPart.Document.Save();
doc.Close();

最新更新