有Jacob 的应用实例也可以

解决方案 »

  1.   

    jacob不支持office2000以上的office,要正确运行下列代码必段保证你的电脑上装了office2000或以下的版本!下载jacob包以及jacob.dll文件,将jacob.dll文件的路径加到path中!import com.jacob.com.*;
    import com.jacob.activeX.*;
    import java.io.*;//取得指定目录下面所有的doc文件名称
    public class wordtohtml {
    //------------------------------------------------------------------------------
    //方法原型: change(String paths)
    //功能描述: 将指定目录下面所有的doc文件转化为HTML并存储在相同目录下
    //输入参数: String
    //输出参数: 无
    //返 回 值: 无
    //其它说明: 递归
    //------------------------------------------------------------------------------
      public static void change(String paths, String savepaths) {    File d = new File(paths);
    //取得当前文件夹下所有文件和目录的列表
        File lists[] = d.listFiles();
        String pathss = new String("");//对当前目录下面所有文件进行检索
        for (int i = 0; i < lists.length; i++) {
          if (lists[i].isFile()) {
            String filename = lists[i].getName();
            String filetype = new String("");
    //取得文件类型
            filetype = filename.substring( (filename.length() - 3), filename.length());//判断是否为doc文件
            if (filetype.equals("doc")) {
              System.out.println("当前正在转换......");
    //打印当前目录路径
              System.out.println(paths);
    //打印doc文件名
              System.out.println(filename.substring(0, (filename.length() - 4)));          ActiveXComponent app = new ActiveXComponent("Word.Application"); //启动word          String docpath = paths + filename;
              String htmlpath = savepaths +
                  filename.substring(0, (filename.length() - 4));          String inFile = docpath;
    //要转换的word文件
              String tpFile = htmlpath;
    //HTML文件          boolean flag = false;          try {
                app.setProperty("Visible", new Variant(false));
    //设置word不可见
                Object docs = app.getProperty("Documents").toDispatch();
                Object doc = Dispatch.invoke(docs, "Open", Dispatch.Method,
                                             new Object[] {inFile, new Variant(false),
                                             new Variant(true)}
                                             , new int[1]).toDispatch();
    //打开word文件
                Dispatch.invoke(doc, "SaveAs", Dispatch.Method,
                                new Object[] {tpFile, new Variant(8)}
                                , new int[1]);
    //作为html格式保存到临时文件
                Variant f = new Variant(false);
                Dispatch.call(doc, "Close", f);
                flag = true;
              }
              catch (Exception e) {
                e.printStackTrace();
              }
              finally {
                app.invoke("Quit", new Variant[] {});
              }
              System.out.println("转化完毕!");
            }
          }
          else {
            pathss = paths;
    //进入下一级目录
            pathss = pathss + lists[i].getName() + "\\";
    //递归遍历所有目录
            change(pathss, savepaths);
          }
        }  }//------------------------------------------------------------------------------
    //方法原型: main(String[] args)
    //功能描述: main文件
    //输入参数: 无
    //输出参数: 无
    //返 回 值: 无
    //其它说明: 无
    //------------------------------------------------------------------------------
      public static void main(String[] args) {    String paths = new String("E:\\work\\word\\");
        String savepaths = new String("E:\\work\\html\\");    change(paths, savepaths);  }
    }
      

  2.   

    首先谢谢了,这是转word的,我现在要用到另外一个DLL, 用jacob怎么来调用里面的方法:
    比如,demo.dll里面有个方法  createFile();我怎么通过jacob 在其他的java类中调用这个方法。
    最好有实际的例子。拜托了……
      

  3.   

    其它jacob是基于事件方式进行word处理的。如果像楼主所说,必需修改jacob的源代码:java和.h都需要修改--重新用javah生成.h。
      

  4.   

    这样……那意思是我还得修改原来的DLL(DLL是已经提供好的,没有代码了)。
    jacob不是说 can call com Automation from any Win32 Java VM using JNI……
    我不是用来处理word,用要用到DLL其他的方面。…………时间有限呀,只有两天了……
      

  5.   

    "通过jacob 在其他的java类中调用这个方法。"?不是很明白这句话。
    如果是在java中调用"另外一个DLL"那就好办--用JNI生成一个单独的DLL,用JNI生成的dll调用“另外一个DLL”。
    如果是jacrob调用"另外一个DLL"就不好办了。
      

  6.   

    对呀,就是一个已经有的DLL,没有通过JNI生成……
      

  7.   

    谁能帮我把下面这段代码用C表现出来:谢谢了~!
    Set demo=Server.createobject("DemoReadXml.DemoConnect")    'DemoReadXml.DemoConnect为DLL
    Tmpstr=demo.SplitXml("C:\test.xml","wenjianbianhao","")    'SplitXml为DLL中的一方法
    demo.CreateXmlFile("C:\demo.xml")  …………
    即在C中调用DLL,并使用其中提供的方法……
      

  8.   

    如果确定jacob的配置没有问题,你只要把demo.dll加到注册表里就可以了!!至于怎么注册dll网上随便搜。有问题再说。
      

  9.   

    asjj() :
    是不是只要把jacob的jar文件放到classpath,把demo.dll放到path下面,就可以调用了吗,不需要改jacob的源程序吗?
      

  10.   

    你能介始一个实例吗?我也是刚刚开始做JNI,有些东东不太明白。谢谢你了,我们项目组要用这个东东,很急的……
      

  11.   

    比如我要用到demo.dll中的creatfile()方法
      

  12.   

    建议楼主到如下网址看一下:
    http://java.sun.com/docs/books/tutorial/native1.1/concepts/index.html
      

  13.   

    分就不管了,帮你到底吧。
    -----------------------
    test.cls文件内容如下:
    Public Function myAdd(i1 As Variant, i2 As Variant) As Variant
      myAdd = i1 + i2
    End Function
    注:我生成的是mytest.dll,并且这个dll一定要注册!
    ---------------------------
    java文件调用如下:
        public static void main(String[] args)
         {
      System.runFinalizersOnExit(true);
           Dispatch test = new Dispatch("mytest.test");
    //下面打印“8”
           System.out.println(Dispatch.call(test, "myAdd", new Variant(3), new Variant(5)));
         }
    ---------------------------
    就这么简单!自己再推敲一下吧。
      

  14.   

    楼上的老大们,office2003都可以用的。jacob哪有这么原始用法的。这样用不是累死人。
    package com.XXXX.util.print;//import word.*;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;import com.jacob.com.Variant;
    import it.bigatti.word8.Application;
    import it.bigatti.word8.Cell;
    import it.bigatti.word8.Document;
    import it.bigatti.word8.Documents;
    import it.bigatti.word8.Find;
    import it.bigatti.word8.Table;
    import it.bigatti.word8.Tables;
    import it.bigatti.word8.WdFindWrap;
    import it.bigatti.word8.WdReplace;public class PrintHelper {  //private static Application app = null;
      //private static Documents docs = null;
      private static Object lock = new Object();  private String docTemplate = null;
      private String docFile = null;  private Application app = new Application();
      private Documents docs = null;
      private Document doc = null;  public PrintHelper() {  }  /**
       Constructor.
       docTemplate is src,docFile is dest.
       */
      public PrintHelper(String docTemplate, String docFile) {
        this.docTemplate = docTemplate;
        this.docFile = docFile;
      }  public void preparePrint() throws PrintException {    InputStream in = null;
        OutputStream out = null;
        try {
          in = new FileInputStream(docTemplate);
          out = new FileOutputStream(docFile);      byte[] buf = new byte[1024];
          int reads = 0;
          while ( (reads = in.read(buf)) > 0) {
            out.write(buf);
          }
          out.flush();
        }
        catch (IOException e) {
          java.lang.System.out.print("preparePrint error:" + e.getMessage());
          throw new PrintException("preparePrint error:" + e.getMessage());
        }
        finally {
          try {
            in.close();
          }
          catch (IOException e) {
            java.lang.System.out.print("input stream cant be closed:" + e.getMessage());
            throw new PrintException("input stream cant be closed:" + e.getMessage());
          }
          try {
            out.close();
          }
          catch (IOException e) {
            java.lang.System.out.print("output stream cant be closed:" + e.getMessage());
            throw new PrintException("output stream cant be closed:" + e.getMessage());
          }
        }
      }  /**
       * 开始打印。
       * @throws PrintException
       */
      public void beginPrint() throws PrintException {    try {
          //Application app = sApp.getApp();
          docs = app.getDocuments();
          synchronized (lock) {
            doc = docs.open(new Variant(docTemplate));
            doc.saveAs(new Variant(docFile));
          }
          java.lang.System.out.println("docs have doc num:" + docs.getCount());
        }
        catch (Exception e) {
          e.printStackTrace();
          throw new PrintException(
              "beginPrint error:docFile isn't exists or bag format!");
        }
      }  public void stopPrint() throws PrintException {
        try {
          doc.save();
        }
        catch (Exception e) {
          java.lang.System.out.println("warning:this document cant be saved!");
          throw new PrintException("doc file can't be saved!");
        }
        finally {
          try {
            if (doc != null) {
              doc.close();
            }
          }
          catch (Exception e) {
            java.lang.System.out.println("this document cant be finallize:" +
                                         e.getMessage());      }
          try {
            if (app != null) {
              app.quit();
              app.release();
              app = null;
            }
          }
          catch (Exception e) {
            java.lang.System.out.println("this word application cant be finallize:" +
                                         e.getMessage());
          }
        }
      }  public void setDocTemplate(String docTemplate) {
        this.docTemplate = docTemplate;
      }  public void setDocFile(String docFile) {
        this.docFile = docFile;
      }  public String getDocTemplate() {
        return (this.docTemplate);
      }  public String getDocFile() {
        return (this.docFile);
      }  public File getFile() {
        File file = new File(docFile);
        return file;
      }  public Document getDoc() {
        return this.doc;
      }  public void setDoc(Document doc) {
        this.doc = doc;
      }  /**
        print simple API.
        this return a temp file and must be delete by manual.
       */
      public void insertIntoDoc(
          int tableIndex,
          int rowIndex,
          int colIndex,
          String value
          ) {
        if (doc == null) {
          return;
        }    int max_tbls = doc.range().getTables().getCount();    if (tableIndex > max_tbls) {
          return;
        }
        Table table = doc.range().getTables().item(tableIndex);    int max_rows = table.getRows().getCount();
        int max_cols = table.getColumns().getCount();    if (rowIndex > max_rows) {
          return;
        }
        if (colIndex > max_cols) {
          return;
        }
        try {
          Cell cell = table.cell(rowIndex, colIndex);
          cell.getRange().insertAfter(value);
        }
        catch (Exception e) {
          java.lang.System.out.println("warnning:the insertIntoDoc method ivoke failed!");
          java.lang.System.out.println("detail:table(" + tableIndex +
                                       ")-row(" + rowIndex + ")-col(" + colIndex + ")" +
                                       "--text:" + value);
          e.printStackTrace();
        }
      }  /**
        print simple API.
        this return a temp file and must be delete by manual.
       */
      public void insertEmbededTable(
          int tableIndex,
          int rowIndex,
          int colIndex,
          int subTableIndex,
          int subRowIndex,
          int subColIndex,
          String value
          ) {
        if (doc == null) {
          return;
        }
        int max_tbls = doc.range().getTables().getCount();    if (tableIndex > max_tbls) {
          return;
        }
        Table table = doc.range().getTables().item(tableIndex);    int max_rows = table.getRows().getCount();
        int max_cols = table.getColumns().getCount();    if (rowIndex > max_rows) {
          return;
        }
        if (colIndex > max_cols) {
          return;
        }
        try {
          Cell cell = table.cell(rowIndex, colIndex);
          int subMax_tbls = cell.getRange().getTables().getCount();
          if (subTableIndex > subMax_tbls) {
            return;
          }
          Table table2 = cell.getRange().getTables().item(subTableIndex);      int subMax_rows = table2.getRows().getCount();
          int subMax_cols = table2.getColumns().getCount();      if (subRowIndex > subMax_rows) {
            return;
          }
          if (subColIndex > subMax_cols) {
            return;
          }
          try {
            Cell cell2 = table2.cell(subRowIndex, subColIndex);
            cell2.getRange().insertAfter(value);
          }
          catch (Exception e) {
            System.out.println("warnning:the insertIntoDoc method ivoke failed!");
          }
        }
        catch (Exception e) {
          System.out.println("warnning:the insertIntoDoc method ivoke failed!");
          e.printStackTrace();
        }
      }
      

  15.   

    public void testDocTable() {
        if (doc == null) {
          return;
        }
        int max_tbls = doc.range().getTables().getCount();
        System.out.println("the maxnum of tables is max_tbls:" + max_tbls);
        for (int i = 0; i < max_tbls; i++) {
          Table table = null;
          table = doc.range().getTables().item(i + 1);      int max_rows = table.getRows().getCount();
          int max_cols = table.getColumns().getCount();
          for (int j = 1; j <= max_rows; j++) {
            for (int k = 1; k <= max_cols; k++) {
              try {
                Cell cell = table.cell(j, k);
                cell.getRange().insertAfter("(" + (i + 1) + "-" + j + "-" + k + ")");
              }
              catch (Exception e) {
                java.lang.System.out.println("warnning:the insertIntoDoc method ivoke failed!");
                java.lang.System.out.println("detail:table(" + (i + 1) +
                                             ")-row(" + j + ")-col(" + k + ")" +
                                             "--text:" + "(" + (i + 1) + "-" + j + "-" + k + ")");
                e.printStackTrace();
              }
            }
          }
        }
        try {
          doc.range().getTables().item(1).cell(11,
                                               1).getRange().getTables().item(1).cell(2, 1).getRange().
              insertAfter("asdfasdfasdf\nasdfasdf");
        }
        catch (Exception e) {
          e.printStackTrace();
        }  }  /**
       *replace api
       */
      public void replace(String oldStr, String newStr) {    if (doc == null) {
          return;
        }    if (oldStr == null || "".equals(oldStr)) {
          return;
        }
        if (newStr == null) {
          newStr = "";
        }    try {
          Find find = doc.range().getFind();
          find.execute(new Variant(oldStr),
                       new Variant(false),
                       new Variant(true),
                       new Variant(false),
                       new Variant(false),
                       new Variant(false),
                       new Variant(true),
                       new Variant(WdFindWrap.wdFindContinue),
                       new Variant(false),
                       new Variant(newStr),
                       new Variant(WdReplace.wdReplaceAll)
                       );
        }
        catch (Exception e) {
          java.lang.System.out.println("warnning:the replace method ivoke failed!repalce" +
                                       oldStr + " with " + newStr);
          e.printStackTrace();
        }
      }  public void createTable(int rows, int cols) throws PrintException {
        if (doc == null) {
          return;
        }    Tables tbls = doc.range().getTables();
        try {
          tbls.add(doc.range(), rows, cols);
        }
        catch (Exception e) {
          e.printStackTrace();
          throw new PrintException(e.getMessage());
        }
      }  public void addRow(int tblIdx) throws PrintException {
        if (tblIdx < 1) {
          return;
        }
        if (doc == null) {
          return;
        }    Tables tbls = doc.range().getTables();
        int max_tbls = tbls.getCount();
        if (tblIdx > max_tbls) {
          return;
        }    try {
          Table tbl = tbls.item(tblIdx);
          tbl.getRows().add();
        }
        catch (Exception e) {
          e.printStackTrace();
          throw new PrintException(e.getMessage());
        }
      }//add sub table rows
      public void addSubTableRow(int tblIdx, int rowIndex, int colIndex, int subTblIndex) throws
          PrintException {
        if (tblIdx < 1) {
          return;
        }
        if (doc == null) {
          return;
        }    Tables tbls = doc.range().getTables();
        int max_tbls = tbls.getCount();
        if (tblIdx > max_tbls) {
          return;
        }    try {
          Table tbl = tbls.item(tblIdx);
          tbl.getRows().add();
        }
        catch (Exception e) {
          e.printStackTrace();
          throw new PrintException(e.getMessage());
        }
      }  //sample.
      public static void main(String[] args) {
        try {
          PrintHelper ph = new PrintHelper();
          ph.setDocFile("c:/test.doc");
          ph.setDocTemplate("c:/test1.doc");
          ph.beginPrint();      ph.replace("[bbb]", "bbbffffffff");      ph.stopPrint();      //get the file
          File file = ph.getFile();
        }
        catch (Exception e) {
          e.printStackTrace();
        }
      }
    }
      

  16.   

    it.bigatti.word8是我根据bigatti包装工具生成的,你到网上找一下例子。只要vba可以用的,jacob都有相同的用法。vb的api提示需要的那个文件,就是那个工具需要的文件,是*.olb
      

  17.   

    com.jacob.com.ComFailException: Can't get object clsid from progid
    at com.jacob.com.Dispatch.createInstance(Native Method)
    at com.jacob.com.Dispatch.<init>(Dispatch.java)
    at com.pensun.plugin.Cxacdemo.main(Cxacdemo.java:30)
    Exception in thread "main" 
    ---------------------------------------------------------------------
    这是什么错误
      

  18.   

    方便的话,把你那个dll发给我,我来调一下
    [email protected]
      

  19.   

    我的DLL是deiphi生成的,这应该跟这个没什么关系吧
      

  20.   

    如果是标准的dll,不用注册就可以用。
    vc和vb生成的dll,我在java用过,deiphi的没用过。不过照错误提示来看,还是配置问题。
      

  21.   

    asjj():
    我已经给你发邮件了,现在我实在是没办法了。任务很紧,还有其它很多事要做,完成之后,一定重分相谢!
      

  22.   

    解决了,谢谢你asjj() ,谢谢大家。
    尽管是身无分文了,但心里高兴。
      

  23.   

    import com.jacob.com.*;
    import com.jacob.activeX.*;
    import java.io.*;//取得指定目录下面所有的doc文件名称
    public class wordtohtml {
    //------------------------------------------------------------------------------
    //方法原型: change(String paths)
    //功能描述: 将指定目录下面所有的doc文件转化为HTML并存储在相同目录下
    //输入参数: String
    //输出参数: 无
    //返 回 值: 无
    //其它说明: 递归
    //------------------------------------------------------------------------------
      public static void change(String paths, String savepaths) {    File d = new File(paths);
    //取得当前文件夹下所有文件和目录的列表
        File lists[] = d.listFiles();
        String pathss = new String("");//对当前目录下面所有文件进行检索
        for (int i = 0; i < lists.length; i++) {
          if (lists[i].isFile()) {
            String filename = lists[i].getName();
            String filetype = new String("");
    //取得文件类型
            filetype = filename.substring( (filename.length() - 3), filename.length());//判断是否为doc文件
            if (filetype.equals("doc")) {
              System.out.println("当前正在转换......");
    //打印当前目录路径
              System.out.println(paths);
    //打印doc文件名
              System.out.println(filename.substring(0, (filename.length() - 4)));          ActiveXComponent app = new ActiveXComponent("Word.Application"); //启动word          String docpath = paths + filename;
              String htmlpath = savepaths +
                  filename.substring(0, (filename.length() - 4));          String inFile = docpath;
    //要转换的word文件
              String tpFile = htmlpath;
    //HTML文件          boolean flag = false;          try {
                app.setProperty("Visible", new Variant(false));
    //设置word不可见
                Object docs = app.getProperty("Documents").toDispatch();
                Object doc = Dispatch.invoke(docs, "Open", Dispatch.Method,
                                             new Object[] {inFile, new Variant(false),
                                             new Variant(true)}
                                             , new int[1]).toDispatch();
    //打开word文件
                Dispatch.invoke(doc, "SaveAs", Dispatch.Method,
                                new Object[] {tpFile, new Variant(8)}
                                , new int[1]);
    //作为html格式保存到临时文件
                Variant f = new Variant(false);
                Dispatch.call(doc, "Close", f);
                flag = true;
              }
              catch (Exception e) {
                e.printStackTrace();
              }
              finally {
                app.invoke("Quit", new Variant[] {});
              }
              System.out.println("转化完毕!");
            }
          }
          else {
            pathss = paths;
    //进入下一级目录
            pathss = pathss + lists[i].getName() + "\\";
    //递归遍历所有目录
            change(pathss, savepaths);
          }
        }  }//------------------------------------------------------------------------------
    //方法原型: main(String[] args)
    //功能描述: main文件
    //输入参数: 无
    //输出参数: 无
    //返 回 值: 无
    //其它说明: 无
    //------------------------------------------------------------------------------
      public static void main(String[] args) {    String paths = new String("E:\\work\\word\\");
        String savepaths = new String("E:\\work\\html\\");    change(paths, savepaths);  }
    }请问下这个程序在officexp中怎么实现都