注意jacob只能在windows使用
参考jacob字体修改链接:https://bbs.csdn.net/topics/390149961?spm=1001.2014.3001.5506
参考jacob方法链接:https://blog.csdn.net/jerome_wang/article/details/84676725?spm=1001.2014.3001.5506
对比:
1、添加依赖
<!--添加本地的jacob.jar包 -->
<dependency>
<groupId>jacob</groupId>
<artifactId>jacob</artifactId>
<version>1.19</version>
</dependency>
2、把jacob-1.19-x64.dll放在以下文件夹下面,根据你的系统来使用,我的是64位
文件下载地址:https://pan.baidu.com/s/1Fx543YqaMDgbzyyU3_a2NQ
提取码: 63ai
jdk和jre的bin目录下
C:\Windows\System32和C:\Windows\SysWOW64目录下
3、测试
package com.cao.ftlword.controller;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
import java.io.File;
/**
* 替换文字
*/
public class TestHyperlinks {
public static ActiveXComponent word;
public static Dispatch selection;
public static Dispatch wordFile;
public static Dispatch documents;
//查找指定文字
public static boolean find(String toFindText) {
if (toFindText == null || toFindText.equals("")){
return false;
}
// 从selection所在位置开始查询
Dispatch find = Dispatch.call(selection, "Find").toDispatch();
// 设置要查找的内容
Dispatch.put(find, "Text", toFindText);
// 向前查找
Dispatch.put(find, "Forward", "True");
// 设置格式
Dispatch.put(find, "Format", "True");
// 大小写匹配
Dispatch.put(find, "MatchCase", "True");
// 全字匹配
Dispatch.put(find, "MatchWholeWord", "True");
// 查找并选中
boolean cc = Dispatch.call(find, "Execute").getBoolean();
return cc;
}
// 在当前插入点插入字符串
public static void insertText(String newText) {
Dispatch.put(selection, "Text", newText);
}
public static void main(String[] args) {
String filePath = "E:\\work-peihan\\test.docx";
// 打开文件
word = new ActiveXComponent("Word.Application");
// 后台处理
word.setProperty("Visible", false);
Dispatch documents = word.getProperty("Documents").toDispatch();
Dispatch wordFile = Dispatch.invoke(documents, "Open", Dispatch.Method, new Object[]{filePath, new Variant(true), new Variant(false)}, new int[1]).toDispatch();
selection = word.getProperty("Selection").toDispatch();
if (find("项目名称:")) {
// 光标右移,否则找不到下一个
Dispatch.call(selection, "MoveRight");
insertText("测试插入项目名称1");
// 插入的时候修改字体大小
Dispatch font = Dispatch.get(selection, "Font").toDispatch();
Dispatch.put(font, "Size", new Variant(7.5));
// 光标右移,否则找不到下一个
Dispatch.call(selection, "MoveRight");
}
if(find("报告编号:")){
// 光标右移,否则找不到下一个
Dispatch.call(selection, "MoveRight");
insertText("测试插入报告编号1");
// 光标右移,否则找不到下一个
Dispatch.call(selection, "MoveRight");
}
if(find("项目负责人:")){
// 光标右移,否则找不到下一个
Dispatch.call(selection, "MoveRight");
insertText("测试人1");
}
System.err.println("扫描完毕!");
Dispatch.call(wordFile, "Close", new Variant(true));
Dispatch.call(word, "Quit");
}
}