轻松架起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。