利用jacob给word 指定位置的文字添加超链接,思路先是通过搜索找到指定位置的文字,然后进行替换添加超链接,代码如下:
package com.jstrd.mobile.security;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
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 main(String[] args){
String filePath = "E:\\test.doc";
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();
while (find("指定文字")) {
Object oRange = Dispatch.call(selection, "Range");
Dispatch Hyperlinks = Dispatch.get(wordFile, "Hyperlinks").toDispatch();
Dispatch.invoke(Hyperlinks, "Add", Dispatch.Method, new Object[] { oRange, new Variant("http://www.baidu.com"),new Variant("SubAddress"), new Variant("{}"), new Variant("指定文字")}, new int[4]).toDispatch();
Dispatch.call(selection, "MoveRight");
}
System.out.println("扫描完毕!");
Dispatch.call(wordFile, "Close", new Variant(true));
Dispatch.call(word, "Quit");
}
}