Jacob 将word和excel转换成html

来源:互联网 发布:开放社会基金会 知乎 编辑:程序博客网 时间:2024/05/16 13:41
packageorg.word;

importjava.io.File;

importcom.jacob.activeX.ActiveXComponent;
importcom.jacob.com.Dispatch;
importcom.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;

   
   public static void wordToHtml(String docfile,String htmlfile) throws Exception {
      ActiveXComponent app = newActiveXComponent("Word.Application"); // 启动word
      try {
         app.setProperty("Visible", newVariant(false));
         Dispatch docs =app.getProperty("Documents").toDispatch();
         Dispatch doc = Dispatch.invoke(docs, "Open",Dispatch.Method, new Object[] { docfile, new Variant(false), newVariant(true) },
               new int[1]).toDispatch();
         Dispatch.invoke(doc, "SaveAs", Dispatch.Method,new Object[] { htmlfile, new Variant(WORD_HTML) }, newint[1]);
         Variant f = new Variant(false);
         Dispatch.call(doc, "Close", f);
         File file = new File(htmlfile);
         if (file.exists()) {
            System.out.print("可读:");
            System.out.println(file.canRead());
            System.out.print("可写:");
            System.out.println(file.canWrite());
            System.out.print("可执行:");
            System.out.println(file.canExecute());
         } else {
            System.out.println("file notfound");
         }
      } catch (Exception e) {
         throw e;
      } finally {
         app.invoke("Quit", new Variant[]{});
      }
   }

   
   public static void excelToHtml(String xlsfile,String htmlfile) {
      ActiveXComponent app = newActiveXComponent("Excel.Application"); // 启动Excel
      try {
         app.setProperty("Visible", newVariant(false));
         Dispatch excels =app.getProperty("Workbooks").toDispatch();
         Dispatch excel = Dispatch.invoke(excels, "Open",Dispatch.Method,
               new Object[] { xlsfile, new Variant(false), newVariant(true) }, new int[1]).toDispatch();
         Dispatch.invoke(excel, "SaveAs", Dispatch.Method,new Object[] { htmlfile, new Variant(EXCEL_HTML) }, newint[1]);
         Variant f = new Variant(false);
         Dispatch.call(excel, "Close",f);
      } catch (Exception e) {
         e.printStackTrace();
      } finally {
         app.invoke("Quit", new Variant[]{});
      }

   }

   public static void main(String[] args){
      JacobUtil ju = new JacobUtil();
      try {
         ju.wordToHtml("e:\\TEST.docx","e:\\TEST.html");
      } catch (Exception e) {
         // TODO Auto-generated catchblock
         e.printStackTrace();
      }

   }

}


P.S:文件是指路径+文件名。。。

出现过的异常
1.原因:没有dll文件

  Java代码

  Exception in thread "main"java.lang.UnsatisfiedLinkError: no jacob in java.library.path

 解决方案:将jacob.dll文件拷贝到;C:\WINDOWS\system32下


2. 原因:机子上没有装office

  Java代码

  cant get Object cldid fromprogid

 解决方案:……这个不用说了吧


相关文件:http://u.115.com/file/aq80atrq  免费提供31天下载……

原创粉丝点击