本文介紹通過Java后端程序代碼來讀取Word文本和段落格式的方法拄轻。
本次測試環(huán)境如下:
- Word版本:2013
- 編譯環(huán)境:IntelliJ IDEA2018
- Work庫:spire.doc.jar 3.9.0 免費(fèi)版
- JDK版本:1.8.0
通過textrange.getCharacterFormat()方法讀取文本字符串格式敲茄,通過paragraph.getFormat()讀取段落格式,讀取具體文字及段落屬性時(shí)比搭,可支持讀取字體、字號(hào)汹买、文字顏色汽煮、文字背景、文字是否加粗或傾斜睡毒、文字下劃線来惧、大小寫、邊框演顾、上標(biāo)下標(biāo)供搀、行距、段落縮進(jìn)钠至、對齊方式葛虐、段落邊框、背景等等棉钧,下表中羅列了所有可支持讀取的樣式屬性屿脐,供參考:
讀取文本格式 getCharacterFormat():
圖1-1
圖1-2
讀取段落格式:getFormat()
圖2
用于測試的Word文檔:
圖3
Java示例代碼
import com.spire.doc.*;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.documents.TextSelection;
import com.spire.doc.fields.TextRange;
import java.awt.*;
public class GetTextFormat {
public static void main(String[] args) {
//加載Word源文檔
Document doc = new Document();
doc.loadFromFile("test.docx");
//獲取段落數(shù)量
int count = doc.getSections().get(0).getParagraphs().getCount();
System.out.println("總共含有段落數(shù):" + count);
//查找指定文本
TextSelection textSelections = doc.findString("東野圭吾", false, true);
//獲取字體名稱
String fontname = textSelections.getAsOneRange().getCharacterFormat().getFontName();
//獲取字體大小
float fontsize = textSelections.getAsOneRange().getCharacterFormat().getFontSize();
System.out.println("字體名稱:" + fontname +"\n"
+"字體大小:"+fontsize);
//獲取第二段
Paragraph paragraph2 = doc.getSections().get(0).getParagraphs().get(1);
//獲取段落行距
float linespage = paragraph2.getFormat().getLineSpacing();
System.out.println("段落行距:" + linespage);
//遍歷段落中的子對象
for (int z = 0; z < paragraph2.getChildObjects().getCount(); z++)
{
Object obj2 = paragraph2.getChildObjects().get(z);
//判定是否為文本
if (obj2 instanceof TextRange)
{
TextRange textRange2 = (TextRange) obj2;
//獲取文本顏色
Color textcolor = textRange2.getCharacterFormat().getTextColor();
if (!(textcolor.getRGB() == 0))
{
System.out.println("文本顏色:" + textRange2.getText() + textcolor.toString());
}
//獲取字體加粗效果
boolean isbold = textRange2.getCharacterFormat().getBold();
if (isbold == true)
{
System.out.println("加粗文本:" + textRange2.getText());
}
//獲取字體傾斜效果
boolean isitalic = textRange2.getCharacterFormat().getItalic();
if (isitalic == true)
{
System.out.println("傾斜文本:" + textRange2.getText());
}
//獲取文本背景
String text = textRange2.getText();
Color highlightcolor = textRange2.getCharacterFormat().getHighlightColor();//獲取文本的高亮顏色(即突出顯示顏色)
if (!(highlightcolor.getRGB() == 0 ))
{
System.out.println("文本高亮:" + text + highlightcolor.toString());//輸出高亮的文本和顏色
}
Color textbackgroundcolor = textRange2.getCharacterFormat().getTextBackgroundColor();//獲取文字背景(底紋)
if (!(textbackgroundcolor.getRGB()==0))
{
System.out.println("文本背景:" + text + textbackgroundcolor.toString());//輸出有背景的文本和顏色
}
}
}
}
}
運(yùn)行程序,輸入獲取結(jié)果:
圖4
以上是本次全部內(nèi)容的诵⊥蛘ぃ可關(guān)注公眾號(hào)【Office文檔開發(fā)】查看更多Java操作Word的方法。
轉(zhuǎn)載請務(wù)必注明出處I菅薄申钩!