下面是帮助中的代码 --- C# 为 Word 中不同的章节设置不同的页码
在代码第21行报错[截图中第23行], 我是使用linqpad7 在.net6下测试的, 找不到font属性,请看截图
引用的程序集及版本请看截图
- Code: Select all
//创建Document对象
Document doc = new Document();
//加载现有的Word文档
doc.LoadFromFile(@"C:\Users\Administrator\Desktop\Test.docx");
//实例化HeaderFooter对象(指定页码添加位置:页眉或页脚)
HeaderFooter footer = doc.Sections[0].HeadersFooters.Footer;
//在页脚添加段落
Paragraph footerParagraph = footer.AddParagraph();
//在段落添加页码域
footerParagraph.AppendField("page number", FieldType.FieldPage);
//将段落的内容居中
footerParagraph.Format.HorizontalAlignment = HorizontalAlignment.Center;
//创建段落样式,包括字体名称、大小、颜色
ParagraphStyle style = new ParagraphStyle(doc);
style.CharacterFormat.Font = new Font("黑体", 15, FontStyle.Bold);
style.CharacterFormat.TextColor = Color.Black;
doc.Styles.Add(style);
//在段落中应用段落样式
footerParagraph.ApplyStyle(style.Name);
//将第一章的页码样式设置为罗马数字
doc.Sections[0].PageSetup.PageNumberStyle = PageNumberStyle.RomanLower;
//将第二章的页码样式设置为阿拉伯数字
doc.Sections[1].PageSetup.PageNumberStyle = PageNumberStyle.Arabic;
//如果需要页码不从1开始,则需要将RestartPageNumbering属性设置为true,然后再设置起始数字
doc.Sections[1].PageSetup.RestartPageNumbering = true;
doc.Sections[1].PageSetup.PageStartingNumber = 2;
//保存文档
doc.SaveToFile("output.docx", FileFormat.Docx2010);