輕松架起Java連接COM對象的橋梁
問題是在CSDN上一網友提出的將 m$ word 轉換為 xml 的java程序問題(http://www.csdn.net/expert/topic/1091/1091620.xml). 現將一種簡便的方法詳細闡述於下:
1。下在Java-COM連接橋JACOB(http://danadler.com/jacob/),需要jacob.jar和jacob.dll兩個文件就可以了。並把jacob.dll所在目錄設到PATH。
2。調用程序(Exam_2.java)如下:
import java.io.File;
import com.jacob.com.*;
import com.jacob.activeX.*;
public class Exam_2 {
public static void main(String[] args) {
ActiveXComponent app = new ActiveXComponent("Word.Application");//啟動word
String inFile = "H:\Majix-1_2_2_full\sample\my.doc";//要轉換的word文件
String tpFile = "H:\Majix-1_2_2_full\sample\my.htm";//臨時文件
String otFile = "H:\Majix-1_2_2_full\sample\my.xml";//目標文件
boolean flag = false;
try {
app.setProperty("Visible", new Variant(false));//設置word不可見
Object docs = app.getProperty("Documents").toDispatch();
Object doc = Dispatch.invoke(docs,"Open", Dispatch.Method, new Object[]{inFile,new Variant(false), new Variant(true)}, new int[1]).toDispatch();//打開word文件
Dispatch.invoke(doc,"SaveAs", Dispatch.Method, new Object[]{tpFile,new Variant(8)}, new int[1]);//作為html格式保存到臨時文件
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");//啟動excel
try {
app.setProperty("Visible", new Variant(false));//設置excel不可見
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();//打開臨時文件
Dispatch.invoke(workbook,"SaveAs", Dispatch.Method, new Object[]{otFile,new Variant(46)}, new int[1]);//以xml格式保存到目標文件
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。編譯執行(確保jacob.dll在PATH中)
H:mytest>javac -classpath jacob.jar Exam_2.java
H:mytest>java -cp jacob.jar;. Exam_2