C#刪除Word文檔中的段落的方法示例
免費(fèi).NET Word 庫 - Free Spire.Doc for .NET。該庫支持實(shí)現(xiàn)創(chuàng)建、編輯、轉(zhuǎn)換Word文檔等多種操作,可以直接在Visual Studio中通過NuGet搜索 “FreeSpire.Doc”,然后點(diǎn)擊“安裝”將其引用到程序中?;蛘咄ㄟ^該鏈接下載產(chǎn)品包,解壓后再手動(dòng)將dll文件添加引用至程序。
C# 刪除Word中的指定段落
通過 Section.Paragraphs 屬性獲取 ParagraphCollection 對(duì)象后,再用 RemoveAt(int index) 方法可以實(shí)現(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ǎng)h除文檔每一節(jié)中的所有段落,可以通過循環(huán)實(shí)現(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)
{
//判斷當(dāng)前段落是否為空白段落
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文檔中的段落的方法示例的詳細(xì)內(nèi)容,更多關(guān)于C#刪除Word中的段落的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
C#使用StopWatch獲取程序毫秒級(jí)執(zhí)行時(shí)間的方法
這篇文章主要介紹了C#使用StopWatch獲取程序毫秒級(jí)執(zhí)行時(shí)間的方法,涉及C#操作時(shí)間的相關(guān)技巧,需要的朋友可以參考下2015-04-04
詳解C#的設(shè)計(jì)模式編程之抽象工廠模式的應(yīng)用
這篇文章主要介紹了C#的設(shè)計(jì)模式編程之抽象工廠模式的應(yīng)用,注意區(qū)分一下簡單工廠模式、工廠方法模式和抽象工廠模式概念之間的區(qū)別,需要的朋友可以參考下2016-02-02
C# 動(dòng)畫窗體(AnimateWindow)的小例子
C# 動(dòng)畫窗體(AnimateWindow)的小例子,需要的朋友可以參考一下2013-03-03
WinForm窗體調(diào)用WCF服務(wù)窗體卡死問題
C#調(diào)用WebService實(shí)例開發(fā)
C#判斷指定驅(qū)動(dòng)器是否是Fat分區(qū)格式的方法

