0
0

More than 1 year has passed since last update.

Javaを使用してバッチでWordの空白の段落を削除する方法

Last updated at Posted at 2021-12-14

##テストドキュメント、期待される目標ドキュメントの削除した結果

テストに使用されたWord文書を以下のように示します。含まれている空白の段落は、記事の全体的なレイアウトと美的な効果に影響を与えます。
01.png
目標ドキュメントの削除した結果
02.png
##補助ツール
クラスライブラリを使用する:Free Spire.Doc for Java(無料版)
クラスライブラリjarファイルのインポート(参照用の2つのインポートメソッド)
1 公式Webサイトからjarパッケージをダウンロードして解凍し、libフォルダー内のSpire.Doc.jarをJavaプログラムに手動でインポートします。
2 Mavenプログラムにjarをインポートするには、最初にpom.xmlファイルを構成してから、プログラムをインポートし、次のように構成する必要があります。

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

インポートした結果:
03.png

##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("C:\\Users\\Administrator\\Desktop\\Sample.docx");

        //セクションをトラバースする
        for(int i = 0; i< doc.getSections().getCount();i++)
        {
            //sectionを取得する
            Section section = doc.getSections().get(i);

            //セクション内のオブジェクトをトラバースする
            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();
    }
}

以上は今回の記事でした、最後まで読んでいただきありがとうございます。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0