最近在做项目的时候需要这么一个功能,客户有一大堆word格式的模板,需要我们用程序向模板里面填充一些数据,如果是直接重新写一个 Word,用POI或Itext都可以搞定,关键是读取并解析,而且Word里有表格,图片等其他东西,这两个框架要解析就比较麻烦,然而用jacob却可以轻松搞定。
下面是借鉴了别人已经包装好了的代码:
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;
}
this.doc = Dispatch.call(this.words, "Add").toDispatch();
this.readOnly = false;
this.cursor = app.getProperty("Selection").toDispatch();
this.tables = Dispatch.get(this.doc,"Tables").toDispatch();
System.out.println("新建word文档");
return true;
}