我想知道Word文档在C#中使用Interop.Word在页眉/页脚中是否有页码。
我走了这么远
try
{
foreach (Section SectionObj in DocObj.Sections)
{
foreach (HeaderFooter HeaderObj in SectionObj.Footers)
{
if (HeaderObj.Exists && (HeaderObj.Shapes.Count > 0 || !(string.IsNullOrEmpty(HeaderObj.Range.Text) || HeaderObj.Range.Text.Equals("\r"))))
{
if(HeaderObj.PageNumbers.NumberStyle == WdPageNumberStyle.wdPageNumberStyleNumberInDash
|| HeaderObj.PageNumbers.NumberStyle == WdPageNumberStyle.wdPageNumberStyleUppercaseLetter
|| HeaderObj.PageNumbers.NumberStyle == WdPageNumberStyle.wdPageNumberStyleUppercaseRoman
|| HeaderObj.PageNumbers.NumberStyle == WdPageNumberStyle.wdPageNumberStyleNumberInCircle
|| HeaderObj.PageNumbers.NumberStyle == WdPageNumberStyle.wdPageNumberStyleLowercaseRoman
|| HeaderObj.PageNumbers.NumberStyle == WdPageNumberStyle.wdPageNumberStyleLowercaseLetter
|| HeaderObj.PageNumbers.NumberStyle == WdPageNumberStyle.wdPageNumberStyleHindiLetter1)
{
PageNumber = true;
}
}
}
}
}
catch (Exception e) { }
但是检查无法确定它是否是Page编号。我该怎么做才能确定它是否有页码?
答案 0 :(得分:1)
您应该使用PageNumbers.Count属性检查节的页眉和页脚。
private bool HeaderOrFooterHasPageNumber(Word.HeaderFooter headOrFooter)
{
if (headOrFooter != null)
return headOrFooter.PageNumbers.Count > 0;
else
return false;
}
你可以这样称呼......
bool hasNumberPages = false;
Word.Document doc = WordApp.ActiveDocument;
try
{
Word.HeaderFooter headOrFooter = null;
Word.Section section = null;
for (int i = 1; i <= doc.Sections.Count; i++)
{
try
{
section = doc.Sections[i];
if(section != null)
{
headOrFooter = section.Footers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary];
hasNumberPages = HeaderOrFooterHasPageNumber(headOrFooter);
if (hasNumberPages)
break;
headOrFooter = section.Footers[Word.WdHeaderFooterIndex.wdHeaderFooterEvenPages];
hasNumberPages = HeaderOrFooterHasPageNumber(headOrFooter);
if (hasNumberPages)
break;
headOrFooter = section.Footers[Word.WdHeaderFooterIndex.wdHeaderFooterFirstPage];
hasNumberPages = HeaderOrFooterHasPageNumber(headOrFooter);
if (hasNumberPages)
break;
headOrFooter = section.Headers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary];
hasNumberPages = HeaderOrFooterHasPageNumber(headOrFooter);
if (hasNumberPages)
break;
headOrFooter = section.Headers[Word.WdHeaderFooterIndex.wdHeaderFooterEvenPages];
hasNumberPages = HeaderOrFooterHasPageNumber(headOrFooter);
if (hasNumberPages)
break;
headOrFooter = section.Headers[Word.WdHeaderFooterIndex.wdHeaderFooterFirstPage];
hasNumberPages = HeaderOrFooterHasPageNumber(headOrFooter);
if (hasNumberPages)
break;
}
}
finally
{
if(headOrFooter != null)
{
Marshal.ReleaseComObject(headOrFooter);
headOrFooter = null;
}
if (section != null)
Marshal.ReleaseComObject(section);
}
}
}
finally
{
if (doc != null)
Marshal.ReleaseComObject(doc);
}