最近項目中需要在頁面中預覽word檔案,雖說word本身就可以在頁面中開啟,但是有兩個弊端,1是可用戶端必須安裝word, 2是用戶端的環境以及office版本有差異,會造成預覽不穩定。在網上找了一下,發現poi可以把word裝換成txt,但是格式都丟了,只有光禿禿的文本,又搜jacob, 網友們眾說紛紜, 最後還是自己sourceforge上下載jacob並閱讀doc搞定了.
1 goto http://sourceforge.net/projects/jacob-project/ and download latest library of jacob.
下載的zip檔案結構如下:
2 intel cpu的機器拷貝jacob-1.15-M3-x86.dll到%JAVA_HOME%/jre/bin, AMD cpu的機器拷貝jacob-1.15-M3-x64.dll. 不過請確保jre目錄是你正在使用的jre, 因為現在很多eclipse版本自己帶jre. 這個在eclipse windows-> preferences -> installed jres可以查看.
3 拷貝jacob.jar到你項目目錄的lib下面並確保加入到了classpath.
準備工作完畢, 現在就寫程式了.
import com.jacob.activeX.ActiveXComponent; import com.jacob.com.Dispatch; import com.jacob.com.Variant; public class Test { public static void main(String[] args) { ActiveXComponent app = new ActiveXComponent("Word.Application"); app.setProperty("Visible", new Variant(false)); Dispatch doc1 = app.getProperty("Documents").toDispatch(); //開啟aaaa.doc Dispatch doc2 = Dispatch.invoke( doc1, "Open", Dispatch.Method, new Object[]{"e://aaaa.doc", new Variant(false), new Variant(true)}, new int[1] ).toDispatch(); //另存新檔aaaa.html Dispatch.invoke( doc2, "SaveAs", Dispatch.Method, new Object[]{ "c://aaaa.html", new Variant(8)//7為txt格式, 8儲存為html格式 }, new int[1] ); Variant f = new Variant(false); Dispatch.call(doc2, "Close", f); } }
使用起來很簡單.
當然jacob不光可以做word to html, 還可以做很多事情:
Jacob is a Java library that lets Java applications communicate with Microsoft Windows DLLs or COM libraries. It does this through the use of a custom DLL that the Jacob Java classes communicate with via JNI. The library and dll isolate the Java developer from the underlying windows libraries so that the Java developer does not have to write custom JNI code.
更多的功能, 只有在需要的時候自己摸索了.