Word/Excel/PDF檔案轉換成HTML整理

來源:互聯網
上載者:User

項目開發過程中,需求涉及到了各種文檔轉換為HTML或者網頁易顯示格式,現在將實現方式整理如下:

一、使用Jacob轉換Word,Excel為HTML

“JACOB一個Java-COM中介軟體.通過這個組件你可以在Java應用程式中調用COM組件和Win32 libraries。”

首先下載Jacob包,JDK1.5以上需要使用Jacob1.9版本(JDK1.6尚未測試),與先前的Jacob1.7差別不大

1、將壓縮包解壓後,Jacob.jar添加到Libraries中;

2、將Jacob.dll放至“WINDOWS\SYSTEM32”下面。

需要注意的是:

【使用IDE啟動Web伺服器時,系統讀取不到Jacob.dll,例如用MyEclipse啟動Tomcat,就需要將dll檔案copy到MyEclipse安裝目錄的“jre\bin”下面。

一般系統沒有載入到Jacob.dll檔案時,報錯資訊為:“java.lang.UnsatisfiedLinkError: no jacob in java.library.path”】

建立類:

Java代碼

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 * @param docfile WORD檔案全路徑 * @param htmlfile 轉換後HTML存放路徑 */public static void wordToHtml(String docfile, String htmlfile){ActiveXComponent app = new ActiveXComponent("Word.Application"); // 啟動wordtry{app.setProperty("Visible", new Variant(false));Dispatch docs = 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[] {});}}/** * EXCEL轉HTML * @param xlsfile EXCEL檔案全路徑 * @param htmlfile 轉換後HTML存放路徑 */public static void excelToHtml(String xlsfile, String htmlfile){ActiveXComponent app = new ActiveXComponent("Excel.Application"); // 啟動wordtry{app.setProperty("Visible", new Variant(false));Dispatch excels = app.getProperty("Workbooks").toDispatch();Dispatch excel = Dispatch.invoke(excels,"Open",Dispatch.Method,new Object[] { xlsfile, new Variant(false),new Variant(true) }, new int[1]).toDispatch();Dispatch.invoke(excel, "SaveAs", Dispatch.Method, new Object[] {htmlfile, new Variant(EXCEL_HTML) }, new int[1]);Variant f = new Variant(false);Dispatch.call(excel, "Close", f);}catch (Exception e){e.printStackTrace();}finally{app.invoke("Quit", new Variant[] {});}}}

當時我在找轉換控制項時,發現網易也轉載了一偏關於Jacob使用協助,但其中出現了比較嚴重的錯誤:String htmlfile = "C:\\AA";

只指定到了檔案夾一級,正確寫法是String htmlfile = "C:\\AA\\xxx.html";

到此WORD/EXCEL轉換HTML就已經差不多了,相信大家應該很清楚了:)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.