访问页眉或页脚会创建它,但不会创建空页眉或页脚

时间:2013-08-29 06:34:15

标签: c# .net ms-word office-interop

我的应用程序使用带有嵌入式互操作类型的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);

1 个答案:

答案 0 :(得分:4)

修改我能够使用编辑中的信息重现错误。说实话,我不确定为什么范围那样,但如果你正在寻找一个简单的解决办法,这对我有用:

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;