c#给word从第一页到最后一页依次添加页码
时间: 2023-12-09 17:02:27 浏览: 320
以下是使用c#向Word文档添加页码的示例代码:
```csharp
using System;
using Microsoft.Office.Interop.Word;
namespace AddPageNumbersToWord
{
class Program
{
static void Main(string[] args)
{
//创建一个Word应用程序对象
Application wordApp = new Application();
//打开一个现有的Word文档
Document doc = wordApp.Documents.Open(@"C:\example.docx");
//获取文档的总页数
int totalPages = doc.ComputeStatistics(WdStatistic.wdStatisticPages);
//使用循环向每一页添加页码
for (int i = 1; i <= totalPages; i++)
{
//选择文档中的当前页
doc.ActiveWindow.Selection.GoTo(WdGoToItem.wdGoToPage, WdGoToDirection.wdGoToAbsolute, i);
//在页脚位置插入页码
doc.ActiveWindow.Selection.HeaderFooter.PageNumbers.Add(WdPageNumberAlignment.wdAlignPageNumberCenter);
}
//保存并关闭文档
doc.Save();
doc.Close();
//退出Word应用程序
wordApp.Quit();
}
}
}
```
这段代码将打开指定路径的Word文档,并使用循环向每一页的页脚位置添加页码。最后保存并关闭文档,并退出Word应用程序。注意:在运行前请确保已经添加对Microsoft.Office.Interop.Word的引用。
阅读全文
相关推荐


















