在处理 Word 文档时,时常需要删除文档中的段落。比如从网上复制了含有大量冗余段落的内容到文档中以后,就需要删除这些多余的段落从而只保留有用的内容。Spire.Doc for .NET 可以帮助你通过代码快速删除这些段落,而无需借助任何其他软件。本文将介绍用 Spire.Doc for .NET 删除 Word 文档的段落的详细操作步骤。
安装 Spire.Doc for .NET
首先,您需要将 Spire.Doc for.NET 包含的 DLL 文件作为引用添加到您的 .NET 项目中。DLL 文件可以从此链接下载,也可以通过 NuGet 安装。
PM> Install-Package Spire.Doc移除 Word 文档中的指定段落
Spire.Doc for .NET 提供了 ParagraphCollection 类下的 RemoveAt() 方法来删除文档中的段落。
删除指定段落的详细操作步骤如下:
- 创建 Document 类的对象。
- 用 Document.LoadFromFile() 方法加载 Word 文档。
- 用 Document.Section[] 属性获取文档第一节。
- 用 Section.Paragraphs.RemoveAt() 方法删除节中第4段。
- 用 Document.SaveToFile() 方法保存文档。
- C#
- VB.NET
using System;
using Spire.Doc;
namespace RemoveParagraphs
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //创建 Document 类的对象
            Document document = new Document();
            //加载 Word 文档
            document.LoadFromFile("示例.docx");
            //获取文档第一节
            Section section = document.Sections[0];
            //删除节中第4段
            section.Paragraphs.RemoveAt(3);
            
            //保存文档
            document.SaveToFile("删除指定段落.docx", FileFormat.Docx2013);
        }
    }
}Imports System
Imports Spire.Doc
Module Program
    Sub Main(args As String())
        '创建 Document 类的对象 Dim document As Document = New Document '加载 Word 文档
        document.LoadFromFile("示例.docx")
        '获取文档第一节 Dim section As Section = document.Sections(0) '删除节中第4段
        section.Paragraphs.RemoveAt(3)
        '保存文档 document.SaveToFile("删除指定段落.docx",FileFormat.Docx2013) End Sub End Module
移除 Word 文档中所有段落
想要删除 Word 文档的所有段落,可以用 Spire.Doc for .NET 提供的 ParagraphCollection类下的 Clear()方法。
删除所有段落的详细操作步骤如下:
- 创建 Document类的对象。
- 用 Document.LoadFromFile() 方法载入 Word 文档。
- 循环遍历所有节,并用 Section.Paragraphs.Clear()方法删除每个节的所有段落。
- 用 Document.SaveToFile() 方法保存文档。
- C#
- VB.NET
using System;using Spire.Doc;namespace RemoveAllParagraphs{internal class Program{static void Main(string[] args){//创建 Document 类的对象 Document document = new Document();//载入 Word 文档 document.LoadFromFile("示例.docx");//循环遍历所有节 foreach (Section section in document.Sections){//删除节的所有段落 section.Paragraphs.Clear();}//保存文档 document.SaveToFile("删除所有段落.docx",FileFormat.Docx2013);}}}Imports System Imports Spire.Doc Module Program Sub Main(args As String()) '创建 Document 类的对象
        Dim document As Document = New Document()
        '载入 Word 文档 document.LoadFromFile("示例.docx") '循环遍历所有节
        For Each section As Section In document.Sections
            '删除节的所有段落 section.Paragraphs.Clear() Next '保存文档
        document.SaveToFile("删除所有段落.docx", FileFormat.Docx2013)
    End Sub
End Module
申请临时 License
如果您希望删除结果文档中的评估消息,或者摆脱功能限制,请该Email地址已收到反垃圾邮件插件保护。要显示它您需要在浏览器中启用JavaScript。获取有效期 30 天的临时许可证。
 



 
					



