zoukankan      html  css  js  c++  java
  • Java 批量删除Word中的空白段落

    1. 测试文档、期望达到的目标文档效果

    用于测试的Word文档如下所示,包含的空白段落影响文章整体布局及美观性:

    目标文档效果:

    2. 辅助工具

    2.1 使用类库:Free Spire.Doc for Java(免费版

    2.2 类库jar导入(2种导入方法供参考):

       ①. 通过官网下载jar包,解压,手动将lib文件夹下的Spire.Doc.jar导入java程序;

       ②. Maven程序中导入jar需先配置pom.xml文件,然后导入程序,如下配置:

    <repositories>
            <repository>
                <id>com.e-iceblue</id>
                <url>http://repo.e-iceblue.cn/repository/maven-public/</url>
            </repository>
    </repositories>
    <dependencies>
        <dependency>
            <groupId> e-iceblue </groupId>
            <artifactId>spire.doc.free</artifactId>
            <version>3.9.0</version>
        </dependency>
    </dependencies>

    导入结果:

    3. Java代码示例

    import com.spire.doc.*;
    import com.spire.doc.documents.DocumentObjectType;
    import com.spire.doc.documents.Paragraph;
    
    public class DeleteBlankParas {
        public static void main(String[] args) {
            //加载Word测试文档
            Document doc = new Document();
            doc.loadFromFile("test.docx");
    
            //遍历Section
            for(int i = 0; i< doc.getSections().getCount();i++)
            {
                //获取section
                Section section = doc.getSections().get(i);
    
                //遍历section中的对象
                for (int j = 0;j<section.getBody().getChildObjects().getCount();j++)
                {
                    //获取对象类型
                    Object object = section.getBody().getChildObjects().get(j).getDocumentObjectType();
    
                    //遍历段落
                    for(int z = 0 ; z<section.getParagraphs().getCount();z++)
                    {
                        //获取段落
                        Paragraph paragraph = section.getParagraphs().get(z);
    
                        //判断对象类型是否为段落
                        if(object.equals(DocumentObjectType.Paragraph))
                        {
                            //判断段落内容是否为空
                            if(paragraph.getChildObjects().getLastItem() == null)
                            {
                                //删除空白段落
                                section.getBody().getParagraphs().remove(paragraph);
                                z--;
                            }
                        }
                    }
    
                }
            }
    
            //保存文档
            doc.saveToFile("DeleteBlankParas.docx",FileFormat.Docx_2013);
            doc.dispose();
        }
    }

    < 完 >

  • 相关阅读:
    js函数柯理化
    Promise异步编程解决方案
    set和map结构,class类
    原创:用node.js搭建本地服务模拟接口访问实现数据模拟
    原创:微信小程序如何使用自定义组件
    原创:微信小程序开发要点总结
    Nodejs CMS——基于 NestJS/NuxtJS 的完整开源项目
    浅谈js对象之数据属性、访问器属性、Object.defineProperty方法
    Promise初步详解(resolve,reject,catch)
    原生js面向对象实现简单轮播
  • 原文地址:https://www.cnblogs.com/Yesi/p/13924783.html
Copyright © 2011-2022 走看看