刪除 Word 中的空行
Spire.Doc for .NET是一款專門對 Word 文檔進(jìn)行操作的 .NET 類庫。在于幫助開發(fā)人員無需安裝 Microsoft Word情況下,輕松快捷高效地創(chuàng)建、編輯、轉(zhuǎn)換和打印 Microsoft Word 文檔。擁有近10年專業(yè)開發(fā)經(jīng)驗(yàn)Spire系列辦公文檔開發(fā)工具,專注于創(chuàng)建、編輯、轉(zhuǎn)換和打印Word/PDF/Excel等格式文件處理,小巧便捷。
E-iceblue 功能類庫Spire 系列文檔處理組件均由中國本土團(tuán)隊(duì)研發(fā),不依賴第三方軟件,不受其他國家的技術(shù)或法律法規(guī)限制,同時(shí)適配國產(chǎn)操作系統(tǒng)如中科方德、中標(biāo)麒麟等,兼容國產(chǎn)文檔處理軟件 WPS(如 .wps/.et/.dps 等格式
Spire.Doc for.NET 最新下載
技術(shù)交流Q群(767755948)
將網(wǎng)上的內(nèi)容復(fù)制到Word文檔中時(shí),你可能會發(fā)現(xiàn)段落之間有很多空行,這樣不僅會使文檔顯得冗長,而且影響可讀性。在本文中,您將學(xué)習(xí)如何使用Spire.Doc for .NET以編程方式刪除現(xiàn)有 Word 文檔中的空行/空白段落。
為 .NET 安裝 Spire.Doc
首先,您需要添加 Spire.Doc for .NET 包中包含的 DLL 文件作為 .NET 項(xiàng)目中的引用。DLL 文件可以從此鏈接下載或通過NuGet安裝。
PM> Install-Package Spire.Doc
刪除現(xiàn)有 Word 文檔中的空行
詳細(xì)步驟如下:
- 創(chuàng)建一個(gè)文檔實(shí)例。
- 使用Document.LoadFromFile()方法加載示例 Word 文檔。
- 循環(huán)遍歷文檔中的所有段落并確定該段落是否為空白段落。
- 使用DocumentObjectCollection.Remove()方法從文檔中刪除空白段落。
- 使用Document.SaveToFile()方法將文檔保存到另一個(gè)文件。
【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
歡迎下載|體驗(yàn)更多E-iceblue產(chǎn)品
如需獲取更多產(chǎn)品相關(guān)信息請咨詢慧都在線客服