下面是借鉴了别人已经包装好了的代码:
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[1]).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;
}
...
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[1]).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;
}
...