我以前的一个项目也用到了jacob,操作比较复杂需要插入图片、换页符什么的。
开始也是直接找个人家的例子照猫画虎,可后来发现直接用Java写这些东西会
死人的,所以干脆直接在文档中用VBA写了个宏,操作的时候直接用用jacob调用
那个宏,等操作完了直接调用另存为方法。后来无论如何修改我们只修改那个模板
中的VBA,那个Java一行也没有改过。用jacob操作Word说白了也就是把VBA代码换
了种写法而已

解决方案 »

  1.   

    I’m getting a “ComFailException: Can’t map name to dispid”, what should I do?
    If the exception says “com.jacob.com.ComFailException: Can't map name to dispid”: maybe you’re trying to call method that didn't exist in the library...
    也许你在尝试调用库中不存在的方法……
      

  2.   

    Dispatch docs = app.getProperty("Documents").toDispatch();
    Dispatch document = Dispatch.invoke(
    docs,
    "Open",
    Dispatch.Method,
    new Object[] { docfile, new Variant(false),
    new Variant(true) }, new int[1]).toDispatch(); Dispatch shapes = Dispatch.get(document, "Shapes").toDispatch();
    Dispatch.call(shapes, "AddLine", new Variant(30), new Variant(30),
    new Variant(200), new Variant(200)); String Count = Dispatch.get(shapes, "Count").toString(); // shape的个数
    System.out.println("shape个数:" + Count);
    int counts = Integer.parseInt(Count);
    for (int i = 1; i <= counts; i++)
    { // Item 下标从1 开始
    Dispatch shape = Dispatch.call(shapes, "Item", new Variant(i))
    .toDispatch(); // 取得一个shape
    Dispatch lineFormat = Dispatch.get(shape, "Line")
    .toDispatch();
    }
      

  3.   

    上面的代码是测试过的,如果是新文档,取i为1就可以。
    在操作的时候,可以打开word看看,在宏编辑器里,按F2可以查看对象,这样方便调用。