设为首页 加入收藏

TOP

计算机二级辅导:java操作word
2014-11-23 21:52:22 】 浏览:213
Tags:计算机 二级 辅导 :java 操作 word

  最近在做项目的时候需要这么一个功能,客户有一大堆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;


  }


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇Java中Collection、List的使用 下一篇为什么java的文件名必须和公共类..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目