本来没想到自己会为《轻松架起Java连接COM对象的桥梁》作续,而今还写了续二,可知我们网络上探讨技术的网友们还是挺多的,非常欣慰!这次内容是利用jacob实现在word文档中替换字符串。关于jacob的使用这里不详述,请见《轻松架起Java连接COM对象的桥梁》,具体实现如下:
import com.jacob.com.*;
import com.jacob.activeX.*;
public class Exam_9 {
public static void main(String[] args) {
ActiveXComponent app = new ActiveXComponent("Word.Application");//启动word
String inFile = "H:\\Majix-1_2_2_full\\sample\\my.doc";//要替换的word文件
boolean flag = false;
try {
app.setProperty("Visible", new Variant(false));//设置word不可见
Object docs = app.getProperty("Documents").toDispatch();
Object doc = Dispatch.invoke(docs,"Open", Dispatch.Method, new Object[]{inFile,new Variant(false), new Variant(false)}, new int[1]).toDispatch();//打开word文件,注意这里第三个参数要设为false,这个参数表示是否以只读方式打开,因为我们要保存原文件,所以以可写方式打开。
Object content = Dispatch.get(doc, "Content").toDispatch();//提取word文档内容对象
Object finder = Dispatch.get(content, "Find").toDispatch();//提取find对象,也就查找替换的那个对象
Variant f = new Variant(false);
boolean rt = true;
while ( rt ) {
rt = Dispatch.invoke(finder,"Execute", Dispatch.Method, new Object[]{"Old", f, f, f, f, f, f, f, f, "New", new Variant(true)}, new int[1]).toBoolean();//替换Old ---> New
}
Dispatch.call(doc,"Save");//保存
Dispatch.call(doc, "Close", f);
flag = true;
} catch (Exception e) {
e.printStackTrace();
} finally {
app.invoke("Quit", new Variant[] {});
}
}
}
有疑问联系[email protected]
本文地址:http://com.8s8s.com/it/it17687.htm