C# 删除Word文档末的空白段落行
以下内容介绍如何删除Word文档最后的空白段落行。以C#程序代码为例,并附VB.NET代码供参考。
工具/材料
Visual Studio 2013
Word版本:2013
word库版本:free Spire.Doc.dll 10.10
操作方法
01、
准备一个Word测试文档,将文档存入VS项目程序文件夹下,如本次测试路径为:C:\Users\Administrator\Documents\Visual Studio 2013\Projects\RemoveEmptyLines_Doc\RemoveEmptylines2\bin\Debug(文件路径可另行自定义),文档如下,在文末最后含有多个空白无内容段落。
02、
在程序中引入如下必要程序集文件:
03、
键入如下代码:【C#】using Spire.Doc;using Spire.Doc.Documents;using System;namespace RemoveEmptylines2{ class Program { static void Main(string[] args) { //加载Word测试文档 Document doc = new Document(); doc.LoadFromFile("test.docx"); //遍历section节 foreach(Section section in doc.Sections) { //遍历section中的所有子对象 for (int i = 0; i < section.Body.ChildObjects.Count; i++) { //判定对象类型是否Paragraph段落 if (section.Body.ChildObjects[i].DocumentObjectType == DocumentObjectType.Paragraph) { //获取段落 Paragraph para = section.Body.ChildObjects[i] as Paragraph; //删除文末的空白段落 if (String.IsNullOrEmpty(para.Text.Trim())) { section.Body.ChildObjects.Remove(section.Body.LastParagraph); i--; } } } } //保存结果文档 doc.SaveToFile("outputfile.docx", FileFormat.Docx2013); System.Diagnostics.Process.Start("outputfile.docx"); } }}【VB.NET】Imports Spire.DocImports Spire.Doc.DocumentsNamespace RemoveEmptylines2 Class Program Private Shared Sub Main(args As String()) '加载Word测试文档 Dim doc As New Document() doc.LoadFromFile("test.docx") '遍历section节 For Each section As Section In doc.Sections '遍历section中的所有子对象 For i As Integer = 0 To section.Body.ChildObjects.Count - 1 '判定对象类型是否Paragraph段落 If section.Body.ChildObjects(i).DocumentObjectType = DocumentObjectType.Paragraph Then '获取段落 Dim para As Paragraph = TryCast(section.Body.ChildObjects(i), Paragraph) '删除文末的空白段落 If [String].IsNullOrEmpty(para.Text.Trim()) Then section.Body.ChildObjects.Remove(section.Body.LastParagraph) i -= 1 End If End If Next Next '保存结果文档 doc.SaveToFile("outputfile.docx", FileFormat.Docx2013) System.Diagnostics.Process.Start("outputfile.docx") End Sub End ClassEnd Namespace
04、
完成代码后,执行程序,生成结果文档。在文档中可查看空白段落删除效果,如图:
End