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