将OpenXML SDK中的段落匹配到Word文档中的互操作段落

时间:2018-11-08 17:38:39

标签: ms-word vsto openxml-sdk wordprocessingml

当我尝试分析100多个页面的文档中的文本时,Word互操作非常慢。我重新编写了代码,以使用速度更快的OpenXML SDK。我的问题是,一旦我在OpenXML文档中找到了信息,就必须在Word文档中找到它,然后将主窗口滚动到它。为了做到这一点,我必须以某种方式将OpenXML段落与互操作段落进行匹配。我以为互操作段落完全匹配openxml段落,但是我错了。实际上,互操作通常比OpenXML中具有更多的段落。是否有任何技巧或某种信息可以帮助我匹配它们?例如,我发现通常互操作在表中的每一行之后都有一个空的段落。因此,我可能会使用这些信息并牢记在心,但是我担心的不仅仅是我发现的一种情况。

更新

以下是我创建的简单插件的屏幕截图,目的是演示Word文档上interop和openxml段落之间的区别,其内容如下:

MS Word Document Sample 然后,该加载项检索互操作段落列表和OpenXML段落列表并排显示它们:

Side-by-side comparison

以下是我使用的代码:

var document = Globals.ThisAddIn.Application.ActiveDocument;

if (document == null)
    return;

var interopParagraphs = document
    .StoryRanges
    .Cast<Range>()
    .SingleOrDefault(r => r.StoryType == WdStoryType.wdMainTextStory)
    .Paragraphs
    .Cast<Paragraph>()
    .Select(p => p.Range.Text);

var openXmlDocument = WordprocessingDocument.FromFlatOpcString(document.Content.WordOpenXML);

if (openXmlDocument == null)
    return;

var openXmlParagraphs = openXmlDocument
    .MainDocumentPart
    .Document
    .Body
    .Descendants<DocumentFormat.OpenXml.Wordprocessing.Paragraph>()
    .Select(p => p.InnerText);

var compareDialog = new CompareForm(interopParagraphs, openXmlParagraphs);
compareDialog.ShowDialog();

1 个答案:

答案 0 :(得分:0)

将我的评论变成答案。


对于表行,您可以使用Range.IsEndOfRowMark检查是否正在查看行尾段落。

  

如果指定范围被折叠并且位于表的行尾标记,则此属性返回True;否则,返回False。

您也可以使用Range.Information[WdInformation.wdAtEndOfRowMarker]

  

如果指定的选择或范围位于表格的行尾标记,则返回True

尽管文档稍有不同,但该属性的范围也必须折叠。 AFAIK,它们是等效的。

我还注意到,如果您直接访问一个段落(例如Document.Paragraph [4]),这将不起作用。您必须遍历它们才能起作用。似乎没有记录。

相关问题