jacob-word-入门

来源:互联网 发布:有利网 知乎 编辑:程序博客网 时间:2024/06/12 05:59
package com.web.test;import com.jacob.activeX.ActiveXComponent;import com.jacob.com.Dispatch;import com.jacob.com.Variant;public class TestWord {    /*word运行程序对象*/    private ActiveXComponent MsWordApp = null;    /*word文档*/    private Dispatch document = null;    //打开word文档    public void openWord(boolean makeVisible) {        if (MsWordApp == null) {            MsWordApp = new ActiveXComponent("Word.Application");        }        //设置visible属性        Dispatch.put(MsWordApp, "Visible", new Variant(makeVisible));    }    /*新建word文档*/    public void createNewDoc() {        //获取文档集合        Dispatch documents = Dispatch.get(MsWordApp, "Documents").toDispatch();        //调用Add方法向文档集合中添加一个新的word文件        document = Dispatch.call(documents, "Add").toDispatch();    }    /*向word中写入字符串信息*/    public void insertText(String textToInsert) {        /*获取当前执行写入的位置,如果是新文档则为文档的开始*/        Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch();        //将字符串写入        Dispatch.put(selection,"Text", textToInsert);    }    /*实现文件"另存为"功能*/    public void saveFileAs(String fileName) {        Dispatch.call(document, "SaveAs",fileName);    }    /*实现文件打印功能*/    public void printFile(){        Dispatch.call(document, "PrintOut");    }    /*关闭文档*/    public void closeDoc(){        /*         * 0-关闭文档时,不保存改变的信息         * -1-关闭文档时,保存改变的信息         * -2-关闭文档时,提示是否保存改变的信息,请求确认         * */        Dispatch.call(document,"Close",new Variant(0));        document = null;    }    //quit out    public void closeWord(){        Dispatch.call(MsWordApp, "Quit");        MsWordApp = null;        document = null;    }    public static void main(String[] args) {        TestWord word = new TestWord();        word.openWord(true);        word.createNewDoc();        word.insertText("Hello,world!");    }}
0 0
原创粉丝点击