- ActiveXComponent activeXApp = null;
- File file = new File(localFilePath);
- try {
- activeXApp = new ActiveXComponent("Word.Application");
- activeXApp.setProperty("Visible", new Variant(false));
- Dispatch docs = activeXApp.getProperty("Documents").toDispatch();
- Dispatch doc = Dispatch.invoke(
- docs,
- "Open",
- Dispatch.Method,
- new Object[] { file.getAbsolutePath(),
- new Variant(false), new Variant(false) },
- new int[1]).toDispatch();
- Variant matchCase = new Variant(true);
- // 禁用通配符,下次写一篇介绍Word通配符查询的
- Variant matchWildcards = new Variant(false);
- Variant forward = new Variant(true);
- Variant matchWholeWord = new Variant(false);
- Variant matchSoundsLike = new Variant(false);
- Variant matchAllWordForms = new Variant(false);
- Variant format = new Variant(false);
- Variant wrap = new Variant(1);
- Variant replace = new Variant(2);
- // 也可以用Selection对象
- Dispatch content = Dispatch.get(doc, "Content").toDispatch();
- Dispatch finder = Dispatch.get(content, "Find").toDispatch();
- boolean rt = true;
- while (rt) {
- rt = Dispatch.invoke(
- finder,
- "Execute",
- Dispatch.Method,
- new Object[] { "originalCharacterString", matchCase, matchWholeWord,
- matchWildcards, matchSoundsLike,
- matchAllWordForms, forward, wrap, format, "replaceCharacterString",
- new Variant(true), replace }, new int[1])
- .getBoolean();
- }
- Dispatch.call(doc, "Save");
- Dispatch.call(doc, "Close", new Variant(false));
- } catch (Exception e) {
- throw e;
- } finally {
- if (activeXApp != null) {
- activeXApp.invoke("Quit", new Variant[] {});
- }
- ComThread.Release();
- }
From: http://jlusdy.javaeye.com/blog/183004