C#删除Word文档末的空白段落行

作者:佚名  浏览量:203  发布时间:2023-06-12

以下内容介绍如何删除Word文档最后的空白段落行。以C#程序代码为例,并附VB.NET代码供参考。

01020304操作方法01

准备一个Word测试文档,将文档存入VS项目程序文件夹下,如本次测试路径为:C:\Users\Administrator\Documents\Visual Studio 2013\Projects\RemoveEmptyLines_Doc\RemoveEmptylines2\bin\Debug(文件路径可另行自定义),文档如下,在文末最后含有多个空白无内容段落。

02

在程序中引入如下必要程序集文件:

03

键入如下代码: 【C#】 using Spire.Doc; using Spire.Doc.Documents; using System; namespace RemoveEmptylines2 { class Program { static void Main(string[] args) { //加载Word测试文档 Document doc = new Document(); doc.LoadFromFile("test.docx"); //遍历section节 foreach(Section section in doc.Sections) { //遍历section中的所有子对象 for (int i = 0; i < section.Body.ChildObjects.Count; i++) { //判定对象类型是否Paragraph段落 if (section.Body.ChildObjects[i].DocumentObjectType == DocumentObjectType.Paragraph) { //获取段落 Paragraph para = section.Body.ChildObjects[i] as Paragraph; //删除文末的空白段落 if (String.IsNullOrEmpty(para.Text.Trim())) { section.Body.ChildObjects.Remove(section.Body.LastParagraph); i--; } } } } //保存结果文档 doc.SaveToFile("outputfile.docx", FileFormat.Docx2013); System.Diagnostics.Process.Start("outputfile.docx"); } } } 【VB.NET】 Imports Spire.Doc Imports Spire.Doc.Documents Namespace RemoveEmptylines2 For Each section As Section In doc.Sections For i As Integer = 0 To section.Body.ChildObjects.Count - 1 Next

本文链接: https://www.bigbaik.com/zhichang/5346.html
免责声明:本文内容来自互联网,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,请联系删除。