---
title: "jacob 实例"
author: "jidisoft"
date: "2010-03-09T20:08:55Z"
tags: []
categories: ["编程语言"]
slug: "jacob"
draft: false
lastmod: "2010-03-09T20:08:55Z"
id: 611492
url: "https://jidisoft.iteye.com/blog/611492"
---

下面是借鉴了别人已经包装好了的代码：

　　import com.jacob.activeX.ActiveXComponent;

　　import com.jacob.com.Dispatch;

　　import com.jacob.com.Variant;

　　public class WordHandle{

　　//运行时的Word程序

　　private ActiveXComponent app;

　　//word对象

　　private Dispatch words;

　　//当前的word文档

　　private Dispatch doc;

　　//当前光标位置

　　private Dispatch cursor;

　　//当前文档是否只读

　　private boolean readOnly;

　　//当前文档中所有表格

　　private Dispatch tables;

　　//当前所在表格

　　private Dispatch table;

　　private int count;

　　public WordHandle()

　　{

　　this.app = new ActiveXComponent("Word.Application");

　　this.app.setProperty("Visible", new Variant(false));    // 设置word不可见

　　words = this.app.getProperty("Documents").toDispatch();

　　this.doc = null;

　　this.cursor = null;

　　this.readOnly = true;

　　this.count = 0;

　　}

　　public boolean open(String fileName, boolean readOnly) throws Exception

　　{

　　if (doc != null)

　　{

　　System.out.println("当前文件未关闭");

　　return false;

　　}

　　this.doc = Dispatch.invoke(this.words, "Open", Dispatch.Method, new Object {fileName, new Variant(false), new Variant(readOnly)}, new int).toDispatch();

　　this.cursor = app.getProperty("Selection").toDispatch();

　　this.tables = Dispatch.get(this.doc,"Tables").toDispatch();

　　this.readOnly = readOnly;

　　this.count = Dispatch.get(Dispatch.get(this.doc, "Words").toDispatch(), "Count").getInt() - 1;

　　System.out.println("打开文件" + fileName + (readOnly ? " ReadOnly" : " Writable"));

　　return true;

　　}

　　public boolean newFile() throws Exception

　　{

　　if (doc != null)

　　{

　　System.out.println("当前文件未关闭");

　　return false;

　　}
...