Java调用COM组件 JACOB

来源:互联网 发布:c语言读取多个字符串 编辑:程序博客网 时间:2024/05/17 06:07

JACORB介绍:

JACOB is a JAVA-COM Bridge that allows you to call COM Automation components from Java. It uses JNI to make native calls to the COM libraries. JACOB runs on x86 and x64 environments supporting 32 bit and 64 bit JVMs

通过JACORB操作COM组件(以Office为例):

package com.nowfox.test.word; 
import com.jacob.activeX.ActiveXComponent; 
import com.jacob.com.ComThread; 
import com.jacob.com.Dispatch; 
import com.jacob.com.variant; 
/** 
* Title: 测试Java Com Bridge 
* Description: 
* Copyright: Copyright (c) 2010 
* Company: NowFox Studio 

* @author nowfox 
* @version 1.0 
* @date 2010-6-30 
*/ 
public class TestOffice 

    public static void printExcel(String path) 
    { 
        ComThread.InitSTA(); 
        ActiveXComponent xl = new ActiveXComponent("Excel.Application"); 
        Dispatch excel = null; 
        try 
        { 
            Dispatch workbooks = xl.getProperty("Workbooks").toDispatch(); 
            // 打开文档 
            excel = Dispatch.call(workbooks, "Open", path).toDispatch(); 
            Dispatch.call(excel, "PrintOut", variant.DEFAULT, variant.DEFAULT, 
                    variant.DEFAULT, variant.DEFAULT, "Smart Print"); 
        } 
        catch (Exception e) 
        { 
            e.printStackTrace(); 
        } 
        finally 
        { 
            // Dispatch.call(excel, "Close"); 
            xl.invoke("Quit"); 
            ComThread.Release(); 
        } 
    } 
    public static void printWord(String path) 
    { 
        ComThread.InitSTA(); 
        ActiveXComponent xl = new ActiveXComponent("Word.Application"); 
        variant oldPrinter = Dispatch.get(xl, "ActivePrinter"); 
        Dispatch doc = null; 
        try 
        { 
            // 不显示文档 
            // Dispatch.put(xl, "Visible", new variant(false)); 
            Dispatch docs = xl.getProperty("Documents").toDispatch(); 
            doc = Dispatch.call(docs, "Open", path).toDispatch(); 
            Dispatch.put(xl, "ActivePrinter", new variant("Smart Print")); 
            Dispatch.call(doc, "PrintOut"); 
        } 
        catch (Exception e) 
        { 
            e.printStackTrace(); 
        } 
        finally 
        { 
            Dispatch.put(xl, "ActivePrinter", oldPrinter); 
            // Dispatch.call(doc, "Close"); 
            xl.invoke("Quit"); 
            ComThread.Release(); 
        } 
    } 
    /** 
     * @param args 
     */ 
    public static void main(String[] args) 
    { 
        // printExcel("D:/temp/1.xls"); 
        printWord("D:/temp/1.doc"); 
    } 
}

原创粉丝点击