分段中断后Word Interop缺少页眉和页脚

时间:2017-10-06 10:14:15

标签: c# ms-word office-interop

我正在使用Word Interop根据我公司的模板和UI输入生成一堆文档(基本上用用户提供的值替换文档的某些区域)。这似乎在每个Find.Execute()上使用Range in Document.StoryRanges方法都可以正常工作,但是,在分节符之后它似乎没有处理页眉和页脚(它在完全正常之前处理它们)。

我如何确保捕获整个文档,页眉,页脚和正文?

我的代码的相关部分如下所示,使用的KVP实际上是在实例化时传递给我的引擎类的find-replace对。

    private void ReplaceFieldsWithValues(string tempFile)
    {
        object missing = Missing.Value;
        Application wordApp = new ApplicationClass();
        wordApp.Documents.Open(tempFile);
        Document doc = wordApp.ActiveDocument;
        object replaceAll = WdReplace.wdReplaceAll;
        foreach (Range range in doc.StoryRanges)
        {
            foreach (KeyValuePair<string, string> referenceValue in _referenceValuePair)
            {
                Find findObject = range.Find;
                findObject.ClearFormatting();
                findObject.Text = $"&{{{referenceValue.Key}}}&";
                findObject.Replacement.ClearFormatting();
                findObject.Replacement.Text = referenceValue.Value;
                findObject.Execute(ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,
                    ref missing, ref replaceAll, ref missing, ref missing, ref missing, ref missing);
            }
        }
        doc.Save();
        doc.Close();
    }

1 个答案:

答案 0 :(得分:0)

Word Interop的文档不是最好的,但我找到了一个解决方案,基本上按部分而不是headerfooter获取range StoryRanges个对象,然后单独处理它们。我将查找和替换代码解压缩到一个单独的方法中,现在我的方法看起来像这样:

    private void ReplaceFieldsWithValues(string tempFile)
    {

        Application wordApp = new ApplicationClass();
        wordApp.Documents.Open(tempFile);
        Document doc = wordApp.ActiveDocument;
        foreach (Range range in doc.StoryRanges)
        {
            foreach (KeyValuePair<string, string> referenceValue in _referenceValuePair)
            {
                FindReplaceInRange(referenceValue.Key,referenceValue.Value,range,true);
            }
        }
        foreach (Section section in doc.Sections)
        {
            foreach (HeaderFooter header in section.Headers)
            {
                foreach (KeyValuePair<string, string> referenceValue in _referenceValuePair)
                {
                    FindReplaceInRange(referenceValue.Key, referenceValue.Value, header.Range, true);
                }
            }
            foreach (HeaderFooter footer in section.Footers)
            {
                foreach (KeyValuePair<string, string> referenceValue in _referenceValuePair)
                {
                    FindReplaceInRange(referenceValue.Key, referenceValue.Value, footer.Range, true);
                }
            }
        }
        doc.Save();
        doc.Close();
    }

现在看来工作正常。