この記事ではWord文書で段落の文字色を変更する方法を紹介します。前のようにSpire.Doc for Javaというライブラリが必要になります。
下準備
1.E-iceblueの公式サイトからFree Spire.doc for Java無料版をダウンロードしてください。
2.IDEを起動して新規プロジェクトを作成してから、インストールされたファイルにあった相応しいSpire.doc.jarを参照に追加してください。
元のファイル
コード
```JAVA 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);
}
}
<h4><strong>完成例</strong></h4>
<p><img src="https://cdn-ak.f.st-hatena.com/images/fotolife/l/lendoris/20210106/20210106114855.png" alt="f:id:lendoris:20210106114855p:plain" title="" class="hatena-fotolife" itemprop="image" /></p>
<p> </p>