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();
    }
}

 

< 完 >

 

posted @ 2020-11-04 10:57  E-iceblue  阅读(634)  评论(0编辑  收藏  举报