此条经验将介绍如何通过C#编程来插入Word分页符和分节符的方法。
工具/原料
Free Spire.Doc for .NET 6.3 (社区版)
Visual Studio
Dll引用
1、下载安装Free Spire.Doc后,在程序中注意添加引用Spire.Doc.dll,dll可在安装路径下的Bin文件夹中获取。
插入Word分页符
1、 在指定段落后插入分页符【C#】using Spire.Doc;using Spire.Doc.Documents;namespace InsertPageBreak_Doc{ class Program { static void Main(string[] args) { //创建实例,加载文件 Document document = new Document(); document.LoadFromFile("test.docx"); //在指定段落末尾,插入分页 document.Sections[0].Paragraphs[1].AppendBreak(BreakType.PageBreak); //保存文件并打开 document.SaveToFile("PageBreak.docx", FileFormat.Docx2010); System.Diagnostics.Process.Start("PageBreak.docx"); } }}
2、在依宏氽墓指定字符串后插入分页【C#】using Spire.Doc;using Spire.Doc.Documents;using Spire.Doc.Fields;namespace InsertPagebreak1_Doc{ class Program { static void Main(string[] args) { //创建实例,加载文件 Document doc = new Document(); doc.LoadFromFile("test.docx"); //查找需要在其后插入分页的字符 TextSelection[] selections = doc.FindAllString("guests", true, true); //遍历文档,插入分页 foreach (TextSelection ts in selections) { TextRange range = ts.GetAsOneRange(); Paragraph paragraph = range.OwnerParagraph; int index = paragraph.ChildObjects.IndexOf(range); Break pageBreak = new Break(doc, BreakType.PageBreak); paragraph.ChildObjects.Insert(index + 1, pageBreak); } //保存并打开文档 doc.SaveToFile("Break.docx", FileFormat.Docx); System.Diagnostics.Process.Start("Break.docx"); } }}
插入Word分节符
1、【C#】using Spire.Doc;using Spire.Doc.Documents;namespace InsertSectionBreak_Doc{ class Program { static void Main(string[] args) { //创建实例,加载word测试文档 Document doc = new Document(); doc.LoadFromFile("test.docx"); //获取指定段落,并插入分页符 doc.Sections[0].Paragraphs[1].InsertSectionBreak(SectionBreakType.NoBreak); //保存并打开文档 doc.SaveToFile("SectionBreak.docx", FileFormat.Docx); System.Diagnostics.Process.Start("SectionBreak.docx"); } }}