在操作Microsoft Word文档时,我们想要对其中某个关键词进行高亮显示,需要一排排挨个找出来,然后再设置背景颜色。这样子很麻烦,浪费时间不说,还有可能会看漏。本文就将推荐一个很方便,快捷,而且不会出错的方法 —— 后端通过 Java 代码查找Word文档中所匹配的文本,然后对其设置高亮显示颜色。
根据匹配文本范围不同,将通过以下两方面进行代码演示。
- 查找并高亮显示Word文档中所有匹配的文本
- 查找并高亮显示Word文档指定段落中的所有匹配文本
使用工具:Spire.Doc for Java (可在其中文官网: www.e-iceblue.cn 下载获取,在lib文件夹下找到spire.Doc.jar,然后将其手动导入Java项目中;或创建 Maven 仓库,在 pom .xml文件下引入以下代码。)
<repositories>
<repository>
<id>com.e-iceblue</id>
<url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.doc</artifactId>
<version>5.2.3</version>
</dependency>
</dependencies>
查找并高亮显示Word文档中所有匹配的文本
Spire.Doc for Java提供了Document.findAllString()方法用于查找整个Word文档中所有匹配的文本,然后再对其设置显示颜色。以下是详细操作步骤:
- 初始化Document对象并加载Word示例文档;
- 使用Document.findAllString()方法查找文档中指定文本;
- 使用 Text Selection.getAsOneRange().getCharacterFormat()方法获取指定文本的字符格式,再使用CharacterFormat.setHighlightColor()方法设置文本的突出显示颜色;
- 最后使用Document.saveTo File ()方法保存结果文档到指定路径。
import com.spire.doc.*;
import com.spire.doc.documents.TextSelection;
import java.awt.*;
public class FindAllString {
public static void main(String[] args) {
//加载Word示例文档
Document document = new Document("sample.docx");
//查找文档中所有“Word”文本
TextSelection[] textSelections = document.findAllString("Word", false, true);
//设置高亮颜色
for (TextSelection selection : textSelections) {
selection.getAsOneRange().getCharacterFormat().setHighlightColor(Color.YELLOW);
}
//保存结果文档
document.saveToFile("output/FindAllString.docx", FileFormat.Docx_2013);
}
}
查找并高亮显示Word文档指定段落中的所有匹配文本
在查找文本前,使用所提供的想法获取文档中指定节和段落,即可只高亮显示某个段落中所有匹配的文本。详细实现步骤如下:
- 初始化Document对象并加载Word示例文档;
- 使用Document.getSections().get()方法获取文档的某个节;
- 使用Section.getParagraphs().get()方法获取指定节的某个段落;
- 使用Document.findAllString()方法查找段落中的指定文本;
- 使用TextSelection.getAsOneRange().getCharacterFormat()方法获取指定文本的字符格式,再使用CharacterFormat.setHighlightColor()方法设置文本的突出显示颜色;
- 最后使用Document.saveToFile()方法保存结果文档到指定路径。
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.Section;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.documents.TextSelection;
import java.awt.*;
public class FindAllStringsInAParagraph {
public static void main(String[] args) {
//加载Word示例文档
Document doc = new Document("sample.docx");
//获取第一节
Section section = doc.getSections().get(0);
//获取第一节的第二段落
Paragraph para = section.getParagraphs().get(1);
//查找段落中所有“Word”文本
TextSelection[] textSelections = para.findAllString("Word", false, true);
//设置高亮颜色
for (TextSelection selection : textSelections)
{
selection.getAsOneRange().getCharacterFormat().setHighlightColor(new Color(255, 255, 0));
}
//保存结果文档
doc.saveToFile("output/FindMatchedStringsInAParagraph.docx", FileFormat.Docx_2013);
}
}