轻松架起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
闽公网安备 35060202000074号