使用jacob对word.excel文件进行完美解析(缺点是不支持linux)

本文介绍了一种使用Java将Word和Excel文档转换为HTML的方法。通过调用ActiveX组件,实现对Microsoft Word和Excel应用程序的自动化操作,进而完成文档格式的转换。

  /**
  * 将Word转换为HTML
  *
  * @param docfile
  * @param htmlfile
  */
 public static void change(String docfile, String htmlfile) {
  logger.info("进入" + TAG + "change()");
  System.out.println("docfile=" + docfile + "  htmlfile=" + htmlfile);
  logger.info("docfile=" + docfile + "  htmlfile=" + htmlfile);

  ActiveXComponent app = null; // 启动word
  try {
   app = new ActiveXComponent("Word.Application"); // 启动word
   app.setProperty("Visible", new Variant(false));
   // 设置word不可见
   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();
   // 打开word文件
   Dispatch.invoke(doc, "SaveAs", Dispatch.Method, new Object[] {
     htmlfile, new Variant(8) }, new int[1]);
   // 作为html格式保存到临时文件
   Variant f = new Variant(false);
   Dispatch.call(doc, "Close", f);
  } catch (Exception e) {
   logger.info("进入" + TAG + "change()" + e);
   // e.printStackTrace();
  } finally {
   app.invoke("Quit", new Variant[] {});
  }
 }

 public static void main(String[] args) {
  change(
    "http:/10.11.0.111:8914/ElectronicMagazine/TemporaryFile/090709163210_1.doc",
    "E://YQ/0907091615261.html");
 }

 

需要将jacob.dll文件放到jdk的bin目录下,不然会报错

 

 

 

  /**
  * 将Excel转换为HTML
  *
  * @param docfile
  * @param htmlfile
  */

ActiveXComponent app = new ActiveXComponent("Excel.Application"); // 启动excel
try {
    app.setProperty("Visible", new Variant(false));
    Dispatch excels = app.getProperty("Workbooks").toDispatch();
    Dispatch excel = Dispatch.invoke(excels, "Open", Dispatch.Method,
        new Object[] {"d:/aaa.xls", new Variant(false), new Variant(true)}, new int[1]).toDispatch();
    Dispatch
        .invoke(excel, "SaveAs", Dispatch.Method, new Object[] {"d:/aaa.html", new Variant(44)}, 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的dll 文件以及jar包 在本博客的资源里面有。可以下载

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值