在编辑Word文档时,为了突出显示某个段落或某个关键词,我们可以改变其默认字体颜色(通常为黑色)为其他醒目的颜色,比如红色,橙色,紫色。手动进行上述操作比较麻烦,而且容易遗漏。此篇文章就将演示如何利用Java代码进行自动操作。

  • 更改整个段落的字体颜色
  • 更改指定文本的字体颜色

JAR包导入

本文代码示例需要用到一款名为Spire.Doc for Java的组件,可通过E-iceblue中文官网获取,解压后找到位于lib文件夹下的Spire.Doc.jar,然后将其手动导入Java项目;除了这个方法外,还可以创建Maven仓库,然后在pom.xml文件中导入以下代码进行产品安装。

com.e-iceblue https://repo.e-iceblue.cn/repository/maven-public/ e-iceblue spire.doc 5.4.2

更改整个段落的字体颜色

以下操作步骤用于演示如何给Word文档的某个指定段落更改字体颜色:

  • 创建一个Document实例;
  • 使用Document.LoadFromFile()方法加载 Word 文档;
  • 使用Document.getSections().get(sectionIndex)方法获取特定的节;
  • 使用Section.getParagraphs().get(paragraphIndex)方法获取想要更改字体颜色的段落;
  • 创建一个ParagraphStyle实例;
  • 使用ParagraphStyle.setName()和ParagraphStyle.getCharacterFormat().setTextColor() 方法设置样式名称和字体颜色;
  • 使用Document.getStyles().add()方法将样式添加到文档中;
  • 使用Paragraph.applyStyle()方法将样式应用于段落;
  • 使用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.ParagraphStyle; import java.awt.*; public class ChangeFontColorForParagraph { public static void main(String[] args) { //创建一个Document实例 Document document = new Document(); //加载Word文档 document.loadFromFile("C:\Users\Tina\Desktop\sample.docx"); //获取第一节 Section section = document.getSections().get(0); //更改第一个段落的文本颜色 Paragraph p1 = section.getParagraphs().get(1); ParagraphStyle s1 = new ParagraphStyle(document); s1.setName("Color1"); s1.getCharacterFormat().setTextColor(new Color(188, 51, 4)); document.getStyles().add(s1); p1.applyStyle(s1.getName()); //更改第二段的文本颜色 Paragraph p2 = section.getParagraphs().get(2); ParagraphStyle s2 = new ParagraphStyle(document); s2.setName("Color2"); s2.getCharacterFormat().setTextColor(new Color(115, 18, 139));; document.getStyles().add(s2); p2.applyStyle(s2.getName()); //保存结果文档 document.saveToFile("output/ChangeParagraphTextColor.docx", FileFormat.Docx); } }

更改指定文本的字体颜色

以下操作步骤是演示如何更改Word文档中指定文本的字体颜色。

  • 创建一个Documen实例;
  • 使用Document.loadFromFile()方法加载Word示例文档;
  • 使用Document.findAllString()方法查找想要更改字体颜色的文本;
  • 循环搜索所有符合的文本并使用 TextSelection.getAsOneRange().getCharacterFormat().setTextColor() 方法更改字体颜色;
  • 使用Document.saveToFile()方法保存结果文档。

import com.spire.doc.Document; import com.spire.doc.FileFormat; import com.spire.doc.documents.TextSelection; import java.awt.*; public class ChangeFontColorForText { public static void main(String[] args) { //创建一个Document实例 Document document = new Document(); //加载Word文档 document.loadFromFile("sample.docx"); //找到要更改字体颜色的文本 TextSelection[] text = document.findAllString("栀子", false, true); //更改搜索文本的字体颜色 for (TextSelection seletion : text) { seletion.getAsOneRange().getCharacterFormat().setTextColor(Color.red); } //保存结果文档 document.saveToFile("output/ChangeCertainTextColor.docx", FileFormat.Docx); } }