如何在C#中使用Microsoft.Office.Interop.Word在word文档中添加页码?

问题描述:

我使用Microsoft.Office.Interop.Word使用C#生成word文件。虽然每页的部分不同,但在页脚中添加页码时,一些页码会重复。如何设置在word文档中添加不同的页码?

I am using Microsoft.Office.Interop.Word to generate word file using C#. While adding page number in footer some of the page number get repeated though section of each page is different. How can I manage to add distinct page number in word document?

您需要使用PageNumbers.Add方法: https://msdn.microsoft.com/en-us/library/ microsoft.office.interop.word.pagenumbers.add%28v = office.15%29.aspx [ ^ ]



You need to use the PageNumbers.Add method: https://msdn.microsoft.com/en-us/library/microsoft.office.interop.word.pagenumbers.add%28v=office.15%29.aspx[^]

wordDoc.Sections(1).Footers(1).PageNumbers.Add (1)


我从使用Interop转移为我的Word文档操作需要OpenXML,因为我想在服务器上生成Word文档,Microsoft建议不要在这种情况下使用Interop - 参见KB 257757)。



由于您遇到分页问题,​​请考虑使用某些第三方OpenXML工具包。因为这些工具包基于在运行时填充数据的单词模板,所以您拥有Word的所有本机功能,包括可以在模板设计中设置的分页。在您的代码中,您根本不需要处理它。



看看这个例子以了解更多信息。
I moved from using Interop to OpenXML for my Word document manipulation needs, because I wanted to generate Word documents on the server and Microsoft advises not to use Interop for such scenarios - see KB 257757).

Since you have problems with pagination, consider using some 3rd party OpenXML toolkit. Because these toolkits are based on word templates, which get filled with data at runtime, you have all the native functionality of Word, including pagination, which could be set at template design. In your code you don't have to deal with it at all.

Take a look at this example at Code Project to find out more.