C# 删除Word文档末的空白段落行

5064次浏览推荐于2021.04.06

以下内容介绍如何删除Word文档最后的空白段落行。以C#程序代码为例,并附VB.NET代码供参考。

    操作方法

    • 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.Doc Imports Spire.Doc.Documents Namespace 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 Class End Namespace

          • 04

            完成代码后,执行程序,生成结果文档。在文档中可查看空白段落删除效果,如图:

            • End

            免责声明:

            本页搜狗指南内容仅代表作者本人意见,若因此产生任何纠纷由作者本人负责,概与搜狗公司无关。本页搜狗指南内容仅供参考,请您根据自身实际情况谨慎操作。尤其涉及您或第三方利益等事项,请咨询专业人士处理。

            0点赞无帮助无帮助
            码字人生~