问题是在CSDN上一网友提出的将 m$ word 转换为 xml 的java程序问题(http://www.csdn.net/expert/topic/1091/1091620.xml)or(http://search.csdn.net/expert/topic/54/5406/2002/10/12/1091620.htm). 现将一种简便的方法详细阐述于下:
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
以上是我为解决将 m$ word 转换为 xml 的java程序问题的通用实现的通用方法,其他COM对象也可以一样的解决。如有问题请Email:[email protected]
本文地址:http://com.8s8s.com/it/it18156.htm