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

来源:搜狗指南时间:2022-03-30 17:05:55

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

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

    工具/材料
    VisualStudio2013
    Word版本:2013
    word库版本:freeSpire.Doc.dll10.10
    操作方法
    01
    准备一个Word测试文档,将文档存入VS项目程序文件夹下,如本次测试路径为:C:\Users\Administrator\Documents\VisualStudio2013\Projects\RemoveEmptyLines_Doc\RemoveEmptylines2\bin\Debug(文件路径可另行自定义),文档如下,在文末最后含有多个空白无内容段落。
    02
    在程序中引入如下必要程序集文件:
    03
    键入如下代码:
    【C#】
    usingSpire.Doc;
    usingSpire.Doc.Documents;
    usingSystem;
    namespaceRemoveEmptylines2
    {
    classProgram
    {
    staticvoidMain(string[]args)
    {
    //加载Word测试文档
    Documentdoc=newDocument();
    doc.LoadFromFile("test.docx");
    //遍历section节
    foreach(Sectionsectionindoc.Sections)
    {
    //遍历section中的所有子对象
    for(inti=0;i<section.Body.ChildObjects.Count;i++)
    {
    //判定对象类型是否Paragraph段落
    if(section.Body.ChildObjects[i].DocumentObjectType==DocumentObjectType.Paragraph)
    {
    //获取段落
    Paragraphpara=section.Body.ChildObjects[i]asParagraph;
    //删除文末的空白段落
    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");
    }
    }
    }
    【】
    ImportsSpire.Doc
    ImportsSpire.Doc.Documents
    NamespaceRemoveEmptylines2
    ClassProgram
    PrivateSharedSubMain(argsAsString())
    '加载Word测试文档
    DimdocAsNewDocument()
    doc.LoadFromFile("test.docx")
    '遍历section节
    ForEachsectionAsSectionIndoc.Sections
    '遍历section中的所有子对象
    ForiAsInteger=0Tosection.Body.ChildObjects.Count-1
    '判定对象类型是否Paragraph段落
    Ifsection.Body.ChildObjects(i).DocumentObjectType=DocumentObjectType.ParagraphThen
    '获取段落
    DimparaAsParagraph=TryCast(section.Body.ChildObjects(i),Paragraph)
    '删除文末的空白段落
    If[String].IsNullOrEmpty(para.Text.Trim())Then
    section.Body.ChildObjects.Remove(section.Body.LastParagraph)
    i-=1
    EndIf
    EndIf
    Next
    Next
    '保存结果文档
    doc.SaveToFile("outputfile.docx",FileFormat.Docx2013)
    System.Diagnostics.Process.Start("outputfile.docx")
    EndSub
    EndClass
    EndNamespace
    04
    完成代码后,执行程序,生成结果文档。在文档中可查看空白段落删除效果,如图:

文章内容来源于网络,不代表本站立场,若侵犯到您的权益,可联系我们删除。(本站为非盈利性质网站) 联系邮箱:rjfawu@163.com