Java, Jacob and Microsoft Word: how to properly handle events?

自古美人都是妖i 提交于 2019-12-12 04:49:10

问题


My goal is to write an java applet application that writes a word document(this document is fetched from DB)in a temporary directory on client machine and opens that document using Jacob.

Through Jacob I need to keep the handle to the opened document, so that after the user closes the document I need to save it back to the DB with the changes.

That said, the first thing I want to know is how to capture a close/exit event through Jacob when the user closes/exits the MS Word document. How can I achieve this?

I tried the code below, which is based in the code i saw in this answer: https://stackoverflow.com/a/12332421/3813385 but it only opens the document and does not listen the closing event...

package demo;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.DispatchEvents;
import com.jacob.com.Variant;

public class WordEventTest { 

  public static void main(String[] args) {
      WordEventTest wordEventTest = new WordEventTest();
      wordEventTest.execute();
  }

  public void execute() {


      String strDir = "D:\\fabricasw\\workspace\\jacob\\WebContent\\docs\\";
      String strInputDoc = strDir + "file_in.doc";

      String pid = "Word.Application";

      ActiveXComponent axc = new ActiveXComponent(pid);
      axc.setProperty("Visible", new Variant(true));
      Dispatch oDocuments = axc.getProperty("Documents").toDispatch();
      Dispatch oDocument = Dispatch.call(oDocuments, "Open", strInputDoc).toDispatch();

      WordEventHandler w = new WordEventHandler();
      new DispatchEvents(oDocument, w);

  }

  public class WordEventHandler {
      public void Close(Variant[] arguments) {
          System.out.println("closed word document");
      }
  }

I would appreciate if you guys post some java code showing how. At least how to obtain the contents of a Microsoft Word document and how to detect the application closing event.


回答1:


For handling events, I got help from this site: http://danadler.com/jacob/

Here is my solution that work:

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import com.jacob.com.DispatchEvents;
import com.jacob.com.Variant;
import com.microsoft.word.WordApplication;
import com.microsoft.word.WordDocument;
import com.microsoft.word.WordDocuments;

public class WordEventDemo {

private WordApplication wordApp = null;
private WordDocuments wordDocs = null;
private WordDocument wordDoc = null;

private WordAppEventListener wordAppEventListener = null;
private WordDocEventListener wordDocEventListener = null;
private List<DispatchEvents> dispatchEvents = new ArrayList<DispatchEvents>();

public WordEventDemo() {
}

/**
 * Start Word, open the document and register listener to Word events
 * 
 * @param docId
 *            The id of the document in the database
 */
public void start(String filename) throws Exception {
    // get document from DB
    File fFile = new File(filename); // replace by your code to retrieve file from your DB

    // open document
    // create WORD instance
    wordApp = new WordApplication();

    // get document list
    wordDocs = wordApp.getDocuments();
    Object oFile = fFile.getAbsolutePath();
    Object oConversion = new Boolean(false);
    Object oReadOnly = new Boolean(false);
    wordDoc = wordDocs.Open(oFile, oConversion, oReadOnly);

    wordDoc.Activate();
    wordApp.setVisible(true);

    // register listeners for the word app and document
    wordAppEventListener = new WordAppEventListener();
    dispatchEvents.add(new DispatchEvents(wordApp, wordAppEventListener));
    wordDocEventListener = new WordDocEventListener();
    dispatchEvents.add(new DispatchEvents(wordDoc, wordDocEventListener));
}

// This is the event interface for the word application
public class WordAppEventListener {
    public WordAppEventListener() {
    }

    /**
     * Triggered when the Word Application is closed.
     */
    public void Quit(Variant[] args) {
        // Perform operations on "Quit" event
        System.out.println("quitting Word!");
    }

    /**
     * Event called by Word Application when it attempt to save a file.<br>
     * For Microsoft API reference, see <a
     * href="http://msdn.microsoft.com/en-us/library/ff838299%28v=office.14%29.aspx"
     * >http://msdn.microsoft.com/en-us/library/ff838299%28v=office.14%29.aspx</a>
     * 
     * @param args
     *            An array of 3 Variants (WARNING, they are not in the same order indicated in the msdn link)
     * @param args
     *            [0] <b>Cancel</b> : False when the event occurs. If the event procedure sets this argument to
     *            True, the document is not saved when the procedure is finished.
     * @param args
     *            [1] <b>SaveAsUI</b> : True to display the Save As dialog box.
     * @param args
     *            [2] <b>Doc</b> : The document that is being saved.
     */
    public void DocumentBeforeSave(Variant[] args) {
        // Perform operations on "DocumentBeforeSave" event
        System.out.println("saving Word Document");
    }
}

// This is the event interface for a word document
public class WordDocEventListener {
    /**
     * Triggered when a Word Document is closed.
     * 
     * @param args
     */
    public void Close(Variant[] args) {
        // Perform operations on "Close" event
        System.out.println("closing document");
    }
}
}

Then I call it simply like the following:

WordEventDemo fixture = new WordEventDemo();
fixture.start("path/to/file.docx");
// add a waiting mechanism (could be linked to the close or quit event), to make it simple here
Thread.sleep(20000);


来源:https://stackoverflow.com/questions/24639627/java-jacob-and-microsoft-word-how-to-properly-handle-events

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!