1

我的应用程序使用带有嵌入式互操作类型的 Microsoft.Office.Interop.Word 版本 12 从 .NET 4.0 WPF 应用程序访问 Word 2007 及更高版本。它基本上扫描给定的 Word 文档,替换一些内容,然后再次保存文档。

因为我可能需要替换页眉/页脚中的内容,所以我必须访问它们。我的问题是,以任何方式访问页眉或页脚似乎都会创建它(显示段落标记),但留下空的页眉或页脚不会像 Word UI 那样再次删除该页眉/页脚。这在具有默认页边距的文档中不是问题,但如果页面的边距较小,则页眉可以将页面内容向下移动,即使页眉只包含一个空段落。

我的问题是:如何在不导致 Word 创建页眉/页脚的情况下检查是否需要处理页眉/页脚,或者如何通过代码删除空的页眉/页脚?

这基本上是我正在使用的代码:

Application application = new Application();
// Just for debugging.
application.Visible = true;
Document document = application.Documents.Open(filename);

foreach (Section section in document.Sections)
{
    HeaderFooter header = section.Headers[WdHeaderFooterIndex.wdHeaderFooterPrimary];

    if (header == null || !header.Exists || header.LinkToPrevious)
    {
        // Header is disabled or linked to previous section.
        continue;
    }

    // We need to swith the view, otherwise some operations in the header
    // might fail.
    // This code is from a recorded Word macro.
    Window activeWindow = application.ActiveWindow;
    if (activeWindow.View.SplitSpecial != WdSpecialPane.wdPaneNone &&
        activeWindow.Panes.Count > 1)
    {
        activeWindow.Panes[2].Close();
    }
    activeWindow.ActivePane.View.Type = WdViewType.wdPrintView;
    activeWindow.ActivePane.View.SeekView = WdSeekView.wdSeekPrimaryHeader;

    // Get the full range of the header. This call causes my problem.
    Range headerRange = header.Range;

    // I'm doing something with 'headerRange' here, but this doesn't affect
    // the problem.

    // This switches the current view out of the header. Usually this also
    // deletes the header if it is empty. But if I accessed 'header.Range'
    // it doesn't delete it. Why?
    activeWindow.ActivePane.View.SeekView = WdSeekView.wdSeekMainDocument;
}

application.Quit(SaveChanges: WdSaveOptions.wdDoNotSaveChanges);
4

1 回答 1

4

编辑我能够使用您编辑的信息重现错误。老实说,我不确定为什么 range 会这样做,但是如果您正在寻找一个简单的解决方法,这对我有用:

activeWindow.ActivePane.View.Type = WdViewType.wdPrintView;
activeWindow.ActivePane.View.SeekView = WdSeekView.wdSeekPrimaryHeader;

//Check for blank headers
activeWindow.ActivePane.Selection.WholeStory();
var text = activeWindow.ActivePane.Selection.Text;
if (!string.IsNullOrEmpty(text) && text.Equals("\r"))
{
    activeWindow.ActivePane.View.SeekView = WdSeekView.wdSeekMainDocument;
    continue;
}
// Get the full range of the header. This call causes my problem.
Range headerRange = header.Range;
于 2013-09-04T13:47:28.410 回答