##概要
人々がWordを使ってレポートまたは論文を編集している時、タイトルが使用されるのはごく普通のことです、特定のニーズにより、それらを従って適応されるため、「スタイル」のオプションでWordのタイトルをすばやく設定できます、以下の画像のように。
ディレクトリを追加する場合、「有効スタイル」を「ディレクトリレベル」に設定することができます。ある程度で言えば、タイトルアウトラインをディレクトリとして使用することもできます。
この記事では、バックエンドのJavaプログラムコードを介してWordのタイトルコンテンツを取得する方法を紹介します。
今回のテスト用Word文書は、下の図に示されています。「タイトルスタイル」と「ディレクトリレベル」は既に関連するセッティングも設置完了しました、タイトルは取得ディレクトリと同じです、タイトルを取得する時目次を獲得すると同じです。
##コードテスト環境
Wordテストのドキュメント:.Docx 2019 Edition.
コンパイル環境:Intellij Idea 2018.
JDKバージョン:1.8.0
Word Jarパッケージ:Free spire.doc.jar 7.11
###Javaコード一覧
import com.spire.doc.*;
import com.spire.doc.documents.Paragraph;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class GetTitle {
public static void main(String[] args)throws IOException {
//Wordテストドキュメントをロードする
Document doc = new Document();
doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\sample.docx");
//ヘッダーの内容を.txtファイルに保存する
File file = new File("GetTitle.txt");
if (file.exists())
{
file.delete();
}
file.createNewFile();
FileWriter fw = new FileWriter(file, true);
BufferedWriter bw = new BufferedWriter(fw);
//sectionをトラバースする
for (int i = 0; i < doc.getSections().getCount(); i++)
{
Section section = doc.getSections().get(i);
//Paragraphをトラバースする
for (int j = 0; j < section.getParagraphs().getCount(); j++)
{
Paragraph paragraph = section.getParagraphs().get(j);
//タイトルを取得する
if ( paragraph.getStyleName().matches("1"))//「見出し1」という内容の段落
{
//段落タイトルのコンテンツを取得する
String text = paragraph.getText();
//txtドキュメントにテキストを書き込む
bw.write("タイトル1: "+ text + "\r");
}
//タイトルを取得する
if ( paragraph.getStyleName().matches("2"))//「見出し2」という内容の段落
{
//段落タイトルのコンテンツを取得する
String text = paragraph.getText();
//txtドキュメントにテキストを書き込む
bw.write("タイトル2: " + text + "\r");
}
//タイトルを取得する
if ( paragraph.getStyleName().matches("3"))//「見出し3」という内容の段落
{
//段落タイトルのコンテンツを取得する
String text = paragraph.getText();
//txtドキュメントにテキストを書き込む
bw.write("タイトル3: " + text+"\r");
}
//タイトルを取得する
if ( paragraph.getStyleName().matches("4"))//「見出し4」という内容の段落
{
//段落タイトルのコンテンツを取得する
String text = paragraph.getText();
//txtドキュメントにテキストを書き込む
bw.write("タイトル4: " + text+"\r");
}
bw.write("\n");
}
}
bw.flush();
bw.close();
fw.close();
}
}
今回のWordタイトル読み取る方法は以上でした、最後まで読んでいただきありがとうございます。