LoginSignup
0
0

More than 3 years have passed since last update.

Java   Word文書で段落の文字色を変更

Posted at

この記事ではWord文書で段落の文字色を変更する方法を紹介します。前のようにSpire.Doc for Javaというライブラリが必要になります。

下準備

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

f:id:lendoris:20210106114703p:plain

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

f:id:lendoris:20210106114719p:plain

元のファイル

f:id:lendoris:20210106114800p:plain

コード

import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.fields.TextRange;

import java.awt.*;

public class ChangeFontColor {
    public static void main(String[] args){
        //Document objectを作成します。
        Document doc = new Document();
        //Wordをロードします。
        doc.loadFromFile("FontColorExample.docx");

        //初めのsectionを取得します。
        Section section = doc.getSections().get(0);
        //初めのsectionで二つ目の段落をを取得します。
        Paragraph p1 = section.getParagraphs().get(1);

        //二つ目の段落をループします。
        for (int i = 0; i < p1.getChildObjects().getCount(); i ++)
        {
            //二つ目の段落のテキストの色を変更します。
            if ( p1.getChildObjects().get(i) instanceof TextRange)
            {
                TextRange tr = (TextRange) p1.getChildObjects().get(i);
                tr.getCharacterFormat().setTextColor(Color.green);
            }
        }

        //三つ目の段落を取得します。 
        Paragraph p2 = section.getParagraphs().get(2);

        //三つ目の段落をループします
        for (int j = 0; j < p2.getChildObjects().getCount(); j ++)
        {
            //三つ目の段落のテキストの色を変更します。
            if ( p2.getChildObjects().get(j) instanceof TextRange)
            {
                TextRange tr = (TextRange) p2.getChildObjects().get(j);
                tr.getCharacterFormat().setTextColor(Color.blue);
            }
        }

        //保存します。
        doc.saveToFile("ChangeFontColor.docx", FileFormat.Docx_2013);
    }
}

完成例

f:id:lendoris:20210106114855p: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