一起学习
轻松架起Java连接COM对象的桥梁
问题是在CSDN上一网友提出的将 m$ word 转换为 xml 的java程序问题(). 现将一种简便的方法详细阐述于下:
1。下在Java-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
下载本文示例代码
轻松架起Java连接COM对象的桥梁轻松架起Java连接COM对象的桥梁轻松架起Java连接COM对象的桥梁轻松架起Java连接COM对象的桥梁轻松架起Java连接COM对象的桥梁轻松架起Java连接COM对象的桥梁轻松架起Java连接COM对象的桥梁轻松架起Java连接COM对象的桥梁轻松架起Java连接COM对象的桥梁轻松架起Java连接COM对象的桥梁轻松架起Java连接COM对象的桥梁轻松架起Java连接COM对象的桥梁
阅读(160) | 评论(0) | 转发(0) |