关于java:Java-在Word文档中突出显示指定文本内容

1次阅读

共计 1540 个字符,预计需要花费 4 分钟才能阅读完成。

在微软 Word 或是 WPS 中,如果咱们想要突出显示指定的文本内容,能够用查找替换来更改格局的形式进行突出显示。但如果咱们不应用微软 Word 和 WPS 等软件,或是想要在咱们的程序中集成这样突出显示指定文本内容的性能,咱们能够应用本文将介绍的办法,应用代码实现突出显示指定文本内容。
本文所应用的办法须要用到收费的 Free Spire.Doc for Java,须要先增加 Jar 文件到我的项目中。

1. 通过 Maven 装置

如果应用 Maven,将以下代码增加到“prom.xml”文件中即可。

<repositories>
        <repository>
            <id>com.e-iceblue</id>
            <name>e-iceblue</name>
         <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.doc.free</artifactId>
        <version>5.2.0</version>
    </dependency>
</dependencies>

2. 手动增加 Jar

从 Free Spire.Doc for Java 官网下载文件包,加压后在我的项目依赖项中增加 Jar 文件即可。

找到并突出显示指定文本内容

突出显示文本通常用增加文字背景色的办法,代码实现须要四个步骤,具体操作步骤如下:

  • 创立 Document 类的对象并载入 Word 文档。
  • Document.findAllString() 办法找到所有“牡蛎”文本。
  • 在所有找到的文本中循环应用 TextSelection.getAsOneRange().getCharacterFormat() 办法获取文本格式,并用 CharacterFormat.setHighlightColor() 办法设置文本突出显示为黄色。
  • Document.saveToFile() 办法保留 Word 文档。
    代码示例:
import com.spire.doc.*;
import com.spire.doc.documents.TextSelection;
import com.spire.doc.formatting.CharacterFormat;
import java.awt.*;

public class FindAndHightText {public static void main(String[] args){
        // 创立 Document 类的对象并载入 Word 文档
        Document document = new Document("Sample.docx");

        // 找到所有“牡蛎”文本
        TextSelection[] textSelections = document.findAllString("牡蛎", false, true);

        // 在所有找到的文本中循环获取文本格式并设置文本突出显示为黄色
        for (TextSelection selection : textSelections) {CharacterFormat characterFormat = selection.getAsOneRange().getCharacterFormat();
            characterFormat.setHighlightColor(Color.YELLOW);
        }

        // 保留 Word 文档
        document.saveToFile("突出显示指定文本内容.docx", FileFormat.Docx_2013);
    }
}

成果示意:

以上代码中的援用的办法均来自收费的 Free Spire.Doc for Java。

正文完
 0