Java 调用word
2013年10月04日
⁄ 综合
⁄ 共 3653字 ⁄ 字号
小 中 大
- package com.test;
- import com.jacob.activeX.ActiveXComponent;
- import com.jacob.com.Dispatch;
- import com.jacob.com.Variant;
- public class WordBean extends java.awt.Panel {
- private ActiveXComponent MsWordApp = null;
- private Dispatch document = null;
- public WordBean() {
- super();
- }
-
- public void openWord(boolean makeVisible) {
- if (MsWordApp == null) {
- MsWordApp = new ActiveXComponent("Word.Application");
- }
-
- Dispatch.put(MsWordApp, "Visible", new Variant(makeVisible));
- }
-
- public void openWordDocument(String openFile) {
- Dispatch documents = Dispatch.get(MsWordApp, "Documents").toDispatch();
- document = Dispatch.invoke(documents, "Open",Dispatch.Method,
- new Object[] { openFile, new Variant(false),
- new Variant(true) }, new int[1]).toDispatch();
- }
-
- public void createNewDocument() {
-
- Dispatch documents = Dispatch.get(MsWordApp, "Documents").toDispatch();
- document = Dispatch.call(documents, "Add").toDispatch();
- }
-
- public void insertText(String textToInsert) {
-
-
-
- Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch();
- Dispatch.put(selection, "Text", textToInsert);
- }
-
- public void saveFileAs(String saveFile) {
- Dispatch.invoke(document, "SaveAs", Dispatch.Method, new Object[] {
- saveFile, new Variant(0) }, new int[1]);
- Variant variant = new Variant(false);
- Dispatch.call(document, "Close", variant);
-
-
- }
- public void printFile() {
-
- Dispatch.call(document, "PrintOut");
- }
-
- public void closeDocument() {
-
-
-
- Dispatch.call(document, "Close", new Variant(0));
- document = null;
- }
-
- public void closeWord() {
- Dispatch.call(MsWordApp, "Quit");
- MsWordApp = null;
- document = null;
- }
-
- public void replace(String oldText, String newText) {
- Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch();
- Dispatch find = MsWordApp.call(selection, "Find").toDispatch();
- Dispatch.put(find, "Text", oldText);
- Dispatch.call(find, "Execute");
- Dispatch.put(selection, "Text", newText);
-
- Dispatch.call(selection, "MoveRight");
-
-
- }
- }
- package com.test;
- public class WordTest {
- public static void main(String[] args) {
- WordBean word = new WordBean();
- word.openWord(false);
-
-
-
-
- word.openWordDocument("d:""1.doc");
- word.replace("2", "xx");
- word.replace("3", "yy");
- word.saveFileAs("d:""2.doc");
-
- word.closeWord();
- }
- }