我的应用程序使用具有嵌入式互操作类型的 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);
请您参考如下方法:
编辑 我能够使用您编辑的信息重现错误。老实说,我不确定为什么 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;
