Java调用COM组件

雪域幽狐 2010-07-02 15:41 阅读:10019


这两天需要用Java调用Word、Excel的打印功能,发现一个组件Jacob(Java COM Bridge)
http://sourceforge.net/projects/jacob-project/
挺不错的,可以直接调用COM组件,当然,这肯定是在windows平台下了
文件下载地址
http://sourceforge.net/projects/jacob-project/files/
使用过程:
把jacob-1.14.3-x86.dll放到System32目录下,引入jacob-1.14.3.jar,就可以开始编写代码了

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

    }

}

0条评论

登陆后可评论