C#刪除Word文檔中的段落的方法示例
免費.NET Word 庫 - Free Spire.Doc for .NET。該庫支持實現(xiàn)創(chuàng)建、編輯、轉(zhuǎn)換Word文檔等多種操作,可以直接在Visual Studio中通過NuGet搜索 “FreeSpire.Doc”,然后點擊“安裝”將其引用到程序中。或者通過該鏈接下載產(chǎn)品包,解壓后再手動將dll文件添加引用至程序。
C# 刪除Word中的指定段落
通過 Section.Paragraphs 屬性獲取 ParagraphCollection 對象后,再用 RemoveAt(int index) 方法可以實現(xiàn)刪除指定索引處的段落。具體代碼如下:
using Spire.Doc;
namespace RemoveParagraphs
{
internal class Program
{
static void Main(string[] args)
{
//加載Word文檔
Document document = new Document();
document.LoadFromFile("南極洲.docx");
//獲取第一節(jié)
Section section = document.Sections[0];
//刪除第四段
section.Paragraphs.RemoveAt(3);
//保存文檔
document.SaveToFile("刪除指定段落.docx", FileFormat.Docx2016);
}
}
}C# 刪除Word中的所有段落
ParagraphCollection 類的 Clear() 方法可以直接刪除指定section中所有段落,要刪除文檔每一節(jié)中的所有段落,可以通過循環(huán)實現(xiàn)。具體代碼如下:
using Spire.Doc;
namespace RemoveAllParagraphs
{
internal class Program
{
static void Main(string[] args)
{
//加載Word文檔
Document document = new Document();
document.LoadFromFile("南極洲.docx");
//遍歷所有節(jié)
foreach (Section section in document.Sections)
{
//刪除段落
section.Paragraphs.Clear();
}
//保存文檔
document.SaveToFile("刪除所有段落.docx", FileFormat.Docx2016);
}
}
}C# 刪除Word中的空白段落
刪除空白段落需要先遍歷每一節(jié)中的所有段落并判斷其中是否包含內(nèi)容,如果為空白行則通過DocumentObjectCollection.Remove() 方法將其刪除。具體代碼如下:
using Spire.Doc;
using Spire.Doc.Documents;
using System;
namespace RemoveEmptyLines
{
class Program
{
static void Main(string[] args)
{
//加載Word文檔
Document doc = new Document();
doc.LoadFromFile("南極洲1.docx");
//遍歷所有段落
foreach (Section section in doc.Sections)
{
for (int i = 0; i < section.Body.ChildObjects.Count; i++)
{
if (section.Body.ChildObjects[i].DocumentObjectType == DocumentObjectType.Paragraph)
{
//判斷當前段落是否為空白段落
if (String.IsNullOrEmpty((section.Body.ChildObjects[i] as Paragraph).Text.Trim()))
{
//刪除空白段落
section.Body.ChildObjects.Remove(section.Body.ChildObjects[i]);
i--;
}
}
}
}
//保存文檔
doc.SaveToFile("刪除空白行.docx", FileFormat.Docx2016);
}
}
}
以上就是C#刪除Word文檔中的段落的方法示例的詳細內(nèi)容,更多關于C#刪除Word中的段落的資料請關注腳本之家其它相關文章!
相關文章
C#使用StopWatch獲取程序毫秒級執(zhí)行時間的方法
這篇文章主要介紹了C#使用StopWatch獲取程序毫秒級執(zhí)行時間的方法,涉及C#操作時間的相關技巧,需要的朋友可以參考下2015-04-04
C#判斷指定驅(qū)動器是否是Fat分區(qū)格式的方法
這篇文章主要介紹了C#判斷指定驅(qū)動器是否是Fat分區(qū)格式的方法,涉及C#中DriveFormat屬性的使用技巧,非常具有實用價值,需要的朋友可以參考下2015-04-04

