Java调用COM组件 JACOB

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"); 
    } 
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值