将网上的内容复制到Word文档中时,你可能会发现段落之间有很多空行,这样不仅会使文档显得冗长,而且影响可读性。在本文中,您将学习如何使用Spire.Doc for .NET以编程方式删除现有 Word 文档中的空行/空白段落。
Spire.Doc for.NET 最新下载https://www.evget.com/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 instance Document doc = new Document(); //Load a sample Word document doc.LoadFromFile(@"D:\Files\input.docx"); //Loop through all paragraphs in the document foreach (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 paragraph if (String.IsNullOrEmpty((section.Body.ChildObjects[i] as Paragraph).Text.Trim())) { //Remove blank paragraphs section.Body.ChildObjects.Remove(section.Body.ChildObjects[i]); i--; } } } } //Save the document doc.SaveToFile("RemoveEmptyLines.docx", FileFormat.Docx2013); } } }
【VB.NET】
Imports Spire.Doc Imports Spire.Doc.Documents Namespace RemoveEmptyLines Class Program Private Shared Sub Main(ByVal args As String()) 'Create a Document instance Dim doc As Document = New Document() 'Load a sample Word document doc.LoadFromFile("D:\Files\input.docx") 'Loop through all paragraphs in the document For Each section As Section In doc.Sections For i As Integer = 0 To section.Body.ChildObjects.Count - 1 'Determine if the paragraph is a blank paragraph If section.Body.ChildObjects(i).DocumentObjectType = DocumentObjectType.Paragraph Then 'Remove blank paragraphs If String.IsNullOrEmpty((TryCast(section.Body.ChildObjects(i), Paragraph)).Text.Trim()) Then section.Body.ChildObjects.Remove(section.Body.ChildObjects(i)) i -= 1 End If End If Next Next 'Save the document doc.SaveToFile("RemoveEmptyLines.docx", FileFormat.Docx2013) End Sub End Class End Namespace