LoginSignup
0
0

More than 3 years have passed since last update.

Java Word 空白行を一気に削除する

Posted at

今回はSpire.Doc for Javaという無料のライブラリを利用して、Word 空白行を一気に削除する方法を紹介します。こうすれば、ワードのページをもっと美しくするので、ぜひ身につけるスキルだと思いますよ。

下準備

1.E-iceblueの公式サイトからFree Spire.doc for Java無料版をダウンロードしてください。

f:id:lendoris:20210407172021p:plain

2.IDEを起動して新規プロジェクトを作成してから、インストールされたファイルにあった相応しいSpire.doc.jarを参照に追加してください。

f:id:lendoris:20210407172033p:plain

元のファイル

f:id:lendoris:20210407172058p:plain

サンプルコード

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

実行結果

f:id:lendoris:20210407172148p:plain

 

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