package com.heyang;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
public class ModifyWordDocument {
public static void main(String[] args) throws Exception {
// 初始化com的線程,非常重要!!使用結束后要調用 realease方法
ComThread.InitSTA();
// 實例化ActiveX組件對象:對word進行操作
ActiveXComponent wrdCom = new ActiveXComponent("Word.Application");
// 獲取Dispatch的Documents對象
Dispatch wrdDocs = wrdCom.getProperty("Documents").toDispatch();
// 設置打開的word應用程序是否可見
wrdCom.setProperty("Visible", new Variant(true));
// 打開一個已經存在的文檔
Dispatch doc = Dispatch.call(wrdDocs, "Open", "c:\\abc.doc")
.toDispatch();
// 獲得當前word文檔文本
Dispatch docSelection = Dispatch.get(wrdCom, "Selection").toDispatch();
// 從selection所在位置開始查詢
Dispatch find = Dispatch.call(docSelection, "Find").toDispatch();
// 設置要查找的內容
Dispatch.put(find, "Text", "測試");
// 向前查找
Dispatch.put(find, "Forward", "True");
// 設置格式
Dispatch.put(find, "Format", "True");
// 大小寫匹配
Dispatch.put(find, "MatchCase", "True");
// 全字匹配
Dispatch.put(find, "MatchWholeWord", "True");
Dispatch.call(find, "Execute").getBoolean();
Dispatch.put(docSelection, "Text", "岳飛");
// 另存為
Dispatch.call(doc, "SaveAs", new Variant("C:\\abc.doc")); // 保存一個新文檔
// 保存關閉
if (doc != null) {
Dispatch.call(doc, "Save");
Dispatch.call(doc, "Close", new Variant(true));
doc = null;
}
// 關閉word文件
wrdCom.invoke("Quit", new Variant[] {});
// 釋放com線程。根據jacob的幫助文檔,com的線程回收不由java的垃圾回收器處理
ComThread.Release();
}
}