本文将介绍如何使用Spire.Doc for Java在Word文档中查找和高亮文本。
在Spire.Doc for Java中有两种方法可以用来查找文本:findString()和findAllString()。其中,findString()方法会查找文档中第一个匹配的文本,而findAllString()方法会查找所有匹配的文本。以下示例将展示如何使用findAllString()方法查找所有匹配的文本并给它们设置高亮颜色。
import com.spire.doc.*;
import com.spire.doc.documents.TextSelection;
import java.awt.*;
public class FindAndHightText {
public static void main(String[] args){
//加载Word文档
Document document = new Document("Input.docx");
//查找所有“荷塘”文本
TextSelection[] textSelections = document.findAllString("荷塘", false, false);
//设置高亮颜色
for (TextSelection selection : textSelections) {
selection.getAsOneRange().getCharacterFormat().setHighlightColor(Color.YELLOW);
}
//保存文档
document.saveToFile("FindAndHightText.docx", FileFormat.Docx_2013);
}
}
生成文档: