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

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

Spire.Doc for.NET 最新下载icon-default.png?t=M7J4https://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

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值