1.确保本机已安装office word 并可以正常运行
2.首先下载Jacob包:将压缩包解压后,Jacob.jar添加到Libraries中;将Jacob.dll放至“WINDOWS\SYSTEM32”下面。
public class ChangMain {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
JacobUtil ju = new JacobUtil();
String docfile = "D:\\题库2.doc";
String htmlfile = "D:\\题库2.html";
ju.wordToHtml(docfile, htmlfile);
System.out.println("转换成功!");
}
}
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
public class JacobUtil {
public static final int WORD_HTML = 8;
public static final int WORD_TXT = 7;
public static final int EXCEL_HTML = 44;
//word 转 html
public void wordToHtml(String docfile,String htmlfile){
ComThread.InitSTA();
ActiveXComponent app = new ActiveXComponent("Word.Application");
try{
//设置word不可见
app.setProperty("Visible", new Variant(false));
//获得documents对象
Dispatch docs = (Dispatch)app.getProperty("Documents").toDispatch();
//打开文件
Dispatch doc = Dispatch.invoke(docs, "Open", Dispatch.Method, new Object[] { docfile, new Variant(false),new Variant(true) }, new int[1]).toDispatch();
//保存新的文件
Dispatch.invoke(doc, "SaveAs", Dispatch.Method, new Object[] {htmlfile, new Variant(WORD_HTML) }, new int[1]);
Variant f = new Variant(false);
Dispatch.call(doc, "Close", f);
} catch (Exception e) {
e.printStackTrace();
} finally {
app.invoke("Quit", new Variant[] {});
ComThread.Release();
}
}
}