Skip to main content
 首页 » 编程设计

c#之自动页码

2024年02月13日14Renyi-Fan

我有一个程序可以打开一个 word 文档并用数据填充它。在页脚中有一些数据,但我也希望页脚中的页数在您创建新页面后更新。我知道这是可能的带有字段代码,但我不知道如何以 C# 字形式输入字段代码。

我想使用类似的东西:

Phone: 00000000 mail: somemail@mail  Page {PAGE} of {NUMPAGE}. 

页脚代码:

Microsoft.Office.Interop.Word.Range footer = section.Footers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range; 
footer.Text = ad.contactinfo(path, gud); 

有没有办法将字段代码放入文档中或者是否有其他解决方案?

请您参考如下方法:

解决了 :D

doc.ActiveWindow.ActivePane.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekCurrentPageFooter; 
Object oMissing = System.Reflection.Missing.Value; 
doc.ActiveWindow.Selection.TypeText("some text \t Page "); 
Object TotalPages = Microsoft.Office.Interop.Word.WdFieldType.wdFieldNumPages; 
Object CurrentPage = Microsoft.Office.Interop.Word.WdFieldType.wdFieldPage; 
doc.ActiveWindow.Selection.Fields.Add(doc.ActiveWindow.Selection.Range, ref CurrentPage, ref oMissing, ref oMissing); 
doc.ActiveWindow.Selection.TypeText(" of "); 
doc.ActiveWindow.Selection.Fields.Add(doc.ActiveWindow.Selection.Range, ref TotalPages, ref oMissing, ref oMissing); 

希望代码少一点,但它有效!