Build a bridge between Java and COM objects
The problem was raised by a netizen on CSDN to convert m $ word into xml java program (http://www.csdn.net/expert/topic/1091/1091620.xml). Now a simple method is described in detail below:
1. Under the Java-COM connection bridge JACOB (http://danadler.com/jacob/), the need for jacob. jar and jacob. dll two files can be. Set the directory where jacob. dll is located to PATH.
2. The calling program (Exam_2.java) is as follows:
Import java. io. File;
Import com.jacb.com .*;
Import com. jacob. activeX .*;
Public class Exam_2 {
Public static void main (String [] args ){
ActiveXComponent app = new ActiveXComponent ("Word. Application"); // start the word
String inFile = "H: \ Majix-1_2_2_full \ sample \ my.doc"; // The word file to be converted
String tpFile = "H: \ Majix-1_2_2_full \ sample \ my.htm"; // temporary file
String otFile = "H: \ Majix-1_2_2_full \ sample \ my. xml"; // target file
Boolean flag = false;
Try {
App. setProperty ("Visible", new Variant (false); // set word invisible
Object docs = app. getProperty ("events"). toDispatch ();
Object doc = Dispatch. invoke (docs, "Open", Dispatch. method, new Object [] {inFile, new Variant (false), new Variant (true)}, new int [1]). toDispatch (); // open the word file
Dispatch. invoke (doc, "SaveAs", Dispatch. method, new Object [] {tpFile, new Variant (8)}, new int [1]); // save it as a temporary file in html Format
Variant f = new Variant (false );
Dispatch. call (doc, "Close", f );
Flag = true;
} Catch (Exception e ){
E. printStackTrace ();
} Finally {
App. invoke ("Quit", new Variant [] {});
}
If (flag ){
App = new ActiveXComponent ("Excel. Application"); // start excel
Try {
App. setProperty ("Visible", new Variant (false); // sets the excel file to be invisible.
Object workbooks = app. getProperty ("Workbooks"). toDispatch ();
Object workbook = Dispatch. invoke (workbooks, "Open", Dispatch. method, new Object [] {tpFile, new Variant (false), new Variant (true)}, new int [1]). toDispatch (); // open a temporary file
Dispatch. invoke (workbook, "SaveAs", Dispatch. method, new Object [] {otFile, new Variant (46)}, new int [1]); // save it to the target file in xml format
Variant f = new Variant (false );
Dispatch. call (workbook, "Close", f );
} Catch (Exception e ){
E. printStackTrace ();
} Finally {
App. invoke ("Quit", new Variant [] {});
Try {
File file = new File (tpFile );
File. delete ();
} Catch (Exception e ){
}
}
}
}
}
3. Compile and execute (ensure that jacob. dll is in PATH)
H: mytest> javac-classpath jacob. jar Exam_2.java
H: mytest> java-cp jacob. jar;. Exam_2