免费.NET Word 库 - Free Spire.Doc for .NET。该库支持实现创建、编辑、转换Word文档等多种操作,可以直接在Visual Studio中通过NuGet搜索 “FreeSpire.Doc”,然后点击“安装”将其引用到程序中。或者通过该链接下载产品包,解压后再手动将dll文件添加引用至程序。
通过 Section.Paragraphs 属性获取 ParagraphCollection 对象后,再用 RemoveAt(int index) 方法可以实现删除指定索引处的段落。具体代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
using Spire.Doc;
namespace RemoveParagraphs { internal class Program { static void Main(string[] args) { //加载Word文档 Document document = new Document(); document.LoadFromFile("南极洲.docx");
//获取第一节 Section section = document.Sections[0];
//删除第四段 section.Paragraphs.RemoveAt(3);
//保存文档 document.SaveToFile("删除指定段落.docx", FileFormat.Docx2016); } } } |
ParagraphCollection 类的 Clear() 方法可以直接删除指定section中所有段落,要删除文档每一节中的所有段落,可以通过循环实现。具体代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
using Spire.Doc;
namespace RemoveAllParagraphs { internal class Program { static void Main(string[] args) { //加载Word文档 Document document = new Document(); document.LoadFromFile("南极洲.docx");
//遍历所有节 foreach (Section section in document.Sections) { //删除段落 section.Paragraphs.Clear(); }
//保存文档 document.SaveToFile("删除所有段落.docx", FileFormat.Docx2016); } } } |
删除空白段落需要先遍历每一节中的所有段落并判断其中是否包含内容,如果为空白行则通过DocumentObjectCollection.Remove() 方法将其删除。具体代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
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);
} } } |