小編今天遇到個問題,正如標題所說的。百度了好久,沒有突破,還是在最后,有了希望!!!
直接附上代碼
/*** doc 格式 */ private static final int DOC_FMT = 0; /*** docx 格式 */ private static final int DOCX_FMT = 12; public static void main(String[] args) { DocFmtConvert dfc = new DocFmtConvert(); String srcDocPath = "D:/test.doc"; String descDocPath = "D:/test.docx"; try { dfc.convertDocFmt(srcDocPath, descDocPath, DOCX_FMT); } catch (Exception e) { e.printStackTrace(); } } /** * 根據格式類型轉換 word 文件 * * @param srcPath 源文件 * @param descPath 目標文件 * @param fmt 所轉格式 */ public File convertDocFmt(String srcPath, String descPath, int fmt) throws Exception { // 實例化ComThread線程與ActiveXComponent ComThread.InitSTA(); ActiveXComponent app = new ActiveXComponent("Word.Application"); try { // 文檔隱藏時進行應用操作 app.setProperty("Visible", new Variant(false)); // 實例化模板Document對象 Dispatch document = app.getProperty("Documents").toDispatch(); // 打開Document進行另存為操作 Dispatch doc = Dispatch.invoke(document, "Open", Dispatch.Method, new Object[] { srcPath, new Variant(true), new Variant(true) }, new int[1]).toDispatch(); Dispatch.invoke(doc, "SaveAs", Dispatch.Method, new Object[] { descPath, new Variant(fmt) }, new int[1]); Dispatch.call(doc, "Close", new Variant(false)); return new File(descPath); } catch (Exception e) { throw e; } finally { // 釋放線程與ActiveXComponent app.invoke("Quit", new Variant[] {}); ComThread.Release(); } }
以上代碼需要正常運行需要 jacob 的支持
下載完成之后,需要將壓縮包中的 jar 文件拷貝到項目中,將 dll 文件拷貝到 C:/windows/system32 下(只能放86的 dll),或者拷貝到當前項目運行的 jdk 的目錄下的 jre/bin 目錄下
如上圖所示,小編的這個項目是用的 jdk7,所以要放到下圖所示
放到 jdk/jre/bin 目錄下時,需要注意自己電腦是多少位的,放置對應的 dll 文件。
小編為了省事就都放了,這樣也不會因為沒有找到合適位數的 dll 文件導致程序無法運行了!
以上內容如有問題,還請大神多多指教!!