Java 查找和高亮Word文本


 

在操作Word文檔的過程中,當我們想要快速查找符合條件的特定內容需要將其標注出來便於自己或他人留意時,我們不可避免的會用到Word的查找和高亮功能。本文將介紹如何Java應用程序中借助Free Spire.Doc for Java快速實現這些功能。

 

 

基本步驟:    

1. 下載Free Spire.Doc for Java包並解壓縮

2. 將lib文件夾下Spire.Doc.jar包作為依賴項導入Java應用程序中。(也可直接通過Maven倉庫安裝JAR包(配置pom.xml文件的代碼見下文

3. 在Java應用程序中新建一個Java Class(此處我命名為FindAndHightText), 然后輸入相應的Java代碼並運行

 

 

 

配置pom.xml文件

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <url>http://repo.e-iceblue.cn/repository/maven-public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.doc.free</artifactId>
        <version>2.7.3</version>
    </dependency>
</dependencies>

 

Java代碼示例

以下示例將展示如何使用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("test.docx");

        //查找所有“探月”文本
        TextSelection[] textSelections = document.findAllString("探月", false, false);

        //設置高亮顏色
        for (TextSelection selection : textSelections) {
            selection.getAsOneRange().getCharacterFormat().setHighlightColor(Color.YELLOW);
        }

        //保存文檔
        document.saveToFile("查找和高亮.docx", FileFormat.Docx_2013);
    }
}

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM