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(); } }
< 完 >
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/202157.html
標籤:Java
上一篇:百萬年薪技術大佬的讀書之旅
