700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > Word控件Spire.Doc 【段落处理】教程(十四):如C#/VB.NET:删除 Word 中的空行

Word控件Spire.Doc 【段落处理】教程(十四):如C#/VB.NET:删除 Word 中的空行

时间:2024-01-22 08:48:47

相关推荐

Word控件Spire.Doc 【段落处理】教程(十四):如C#/VB.NET:删除 Word 中的空行

将网上的内容复制到Word文档中时,你可能会发现段落之间有很多空行,这样不仅会使文档显得冗长,而且影响可读性。在本文中,您将学习如何使用Spire.Doc for .NET以编程方式删除现有 Word 文档中的空行/空白段落。

Spire.Doc 最新下载/product/3368/download

为 .NET 安装 Spire.Doc

首先,您需要添加 Spire.Doc for .NET 包中包含的 DLL 文件作为 .NET 项目中的引用。DLL 文件可以从此链接下载或通过NuGet安装。

PM> Install-Package Spire.Doc

删除现有 Word 文档中的空行

详细步骤如下:

创建一个文档实例。使用Document.LoadFromFile()方法加载示例 Word 文档。循环遍历文档中的所有段落并确定该段落是否为空白段落。使用DocumentObjectCollection.Remove()方法从文档中删除空白段落。使用Document.SaveToFile()方法将文档保存到另一个文件。

【C#】

using Spire.Doc;using Spire.Doc.Documents;using System;namespace RemoveEmptyLines{class Program{static void Main(string[] args){//Create a Document instanceDocument doc = new Document();//Load a sample Word documentdoc.LoadFromFile(@"D:\Files\input.docx");//Loop through all paragraphs in the documentforeach (Section section in doc.Sections){for (int i = 0; i < section.Body.ChildObjects.Count; i++){if (section.Body.ChildObjects[i].DocumentObjectType == DocumentObjectType.Paragraph){//Determine if the paragraph is a blank paragraphif (String.IsNullOrEmpty((section.Body.ChildObjects[i] as Paragraph).Text.Trim())){//Remove blank paragraphssection.Body.ChildObjects.Remove(section.Body.ChildObjects[i]);i--;}}}}//Save the documentdoc.SaveToFile("RemoveEmptyLines.docx", FileFormat.Docx);}}}

【】

Imports Spire.DocImports Spire.Doc.DocumentsNamespace RemoveEmptyLinesClass ProgramPrivate Shared Sub Main(ByVal args As String())'Create a Document instanceDim doc As Document = New Document()'Load a sample Word documentdoc.LoadFromFile("D:\Files\input.docx")'Loop through all paragraphs in the documentFor Each section As Section In doc.SectionsFor i As Integer = 0 To section.Body.ChildObjects.Count - 1'Determine if the paragraph is a blank paragraphIf section.Body.ChildObjects(i).DocumentObjectType = DocumentObjectType.Paragraph Then'Remove blank paragraphsIf String.IsNullOrEmpty((TryCast(section.Body.ChildObjects(i), Paragraph)).Text.Trim()) Thensection.Body.ChildObjects.Remove(section.Body.ChildObjects(i))i -= 1End IfEnd IfNextNext'Save the documentdoc.SaveToFile("RemoveEmptyLines.docx", FileFormat.Docx)End SubEnd ClassEnd Namespace

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。