學習jacob的一點心得

這幾天公司有個項目需要在java環境下處理word,自己在網上搜了一下,主要有兩種方法:一是Jakarta POI,二是jacob(即:JAva COm Bridge),我使用了第二種方法,結合
vba,使用非常方便 ,且功能強大。現就自己使用的一點心得記錄如下。(首先需要將下載的jacob.dll文件拷貝到C:/WINDOWS/system32目錄下,並將jacob.jar添加到CLASSPATH
中。)

1.獲取一個component屬性,需要調用Dispatch的get方法:
Dispatch tablefont = Dispatch.get(tablerange,"Font").toDispatch();
表示獲取Table對應range的Font屬性,相當於vba的如下語法:
tablefont = tablerange.Font

2.設置一個component屬性,需要調用Dispatch的put方法:
Dispatch.put(tablefont ,"Size",new Integer(14));
設置tablefont的字體大小爲14,相當於如下的vba語法:
tablefont.Size = 14

3.調用一個component組件的方法,需要調用Dispatch的call和callN方法(我認爲call方法最終都是調用了callN方法:-),right?)
譬如,下面代碼中的
this.document = Dispatch.call(this.documents, "Open", templateFile).toDispatch();
可以通過下面這行代碼實現同樣操作:-)
this.document = Dispatch.callN(this.documents, "Open", new Object[]{templateFile}).toDispatch();
相當於vba的如下語法:
Documents.Open FileName:=templateFile
最後,記住jacob文檔中的一句話:
Declare an STA thread using ComThread.InitSTA() if all your method calls for that component are going to come from the same thread.
結合上述三點和vba api提供的Objects,Properties,Collections,Methods等自己可以試探處理word的其它元素,如:表格等。羅嗦了這麼多,希望對剛開始接觸jacob的朋友能有點滴

的幫助。
自己也是剛學,不妥錯誤之處,也請不吝賜教[email protected]

我使用的jacob是1.9版本,在jdk1.5下調試通過。
本文以最長用的文本查找替換爲例描述一下jacob的使用方法:
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;


/**
 * @author Stout.Bear
 * 2007/6/28
 *
 */
public class WordSpirit4J{
 public static final int wdReplaceOne = 1; //查找替換一次
 public static final int wdReplaceAll = 2;//查找並替換全部
 
 public static final int wdFindContinue = 1;


 
 
 protected String templateFile;//模版文件
 protected String outputFile;//輸出文件
 
 /*jacob相關*/
 protected ActiveXComponent word;
 protected Dispatch documents;
 protected Dispatch document;
 protected Dispatch selection;
 protected Dispatch range;
 protected Dispatch find;
 protected Dispatch paragraphs;
 protected Dispatch paragraph;
 
 protected Dispatch tables;
 protected Dispatch table;
 protected Dispatch rows;
 protected Dispatch row;
 protected Dispatch cells;
 protected Dispatch cell;
 protected Dispatch cellrange;
 
 /**
  *
  * @param templateFile 模版文件路徑
  * @param outputFile 生成的doc文件路徑
  * @throws IllegalArgumentException templateFile參數不能爲空
  */
 public WordSpirit4J(String templateFile, String outputFile) throws FileNotFoundException
 {
  super();
  if(templateFile!=null && new File(templateFile).exists()){
   this.templateFile = templateFile;
   this.outputFile = outputFile;
   initFields();
  }
  else{
   throw new FileNotFoundException("templateFile must exist and not be null!");
  }
 }

 
 
 /**
  * 初始化jacob組件的相關Dispatch對象參數
  *
  */
 protected void initFields(){
  try {
   this.word = new ActiveXComponent("Word.Application");
   this.word.setProperty("Visible", new Variant(false));
   this.documents = this.word.getProperty("Documents").toDispatch();
   this.document = Dispatch.call(this.documents, "Open", templateFile).toDispatch();
   this.selection = this.word.getProperty("Selection").toDispatch();
   this.find = Dispatch.call(this.selection, "Find").toDispatch();
   this.paragraphs = Dispatch.get(document, "Paragraphs").toDispatch();
   this.tables = Dispatch.get(document, "Tables").toDispatch();
   this.range = Dispatch.get(selection, "Range").toDispatch();
  }
  catch(Exception ex){
   System.out.println(ex.getCause().toString());
   ex.printStackTrace();
  }
 }
 
 /**
  *
  * @param findStr 待查找的字符串
  * @param replaceWith 新字符串
  * @param replaceNum 替換一次還是全部,可能取值爲wdReplaceOne和wdReplaceAll。
  */
 protected void findAndReplace(String findStr,String replaceWith,int replaceNum){
  Boolean f = new Boolean(false);
  Boolean t  = new Boolean(true);
  Object[] args={findStr,t,f,f,f,f,t,new Integer(wdFindContinue),f,replaceWith,new Integer(replaceNum),f,f,f,f};
  Dispatch.callN(this.find, "Execute",args);
 }
 
 /**
  * 關閉模版文件,不保存
  *
  */
 protected void closeTemplate(){
  if(this.templateFile!=null && this.document!=null){
   Dispatch.call(this.document, "Close", new Variant(false));
   this.document = null;
  }
  
 }
 
 /**
  * 以文件的形式保存輸出
  *
  */
 protected void saveAsOutputFile(){
  if(this.document!=null){
   Dispatch.invoke(this.document, "SaveAs", Dispatch.Method, new Object[] {
     this.outputFile, new Variant(0) }, new int[1]);
  }
 }
 
 /**
  * 以流的形式保存輸出
  * @return 返回生成的doc文檔的輸出流
  *
  */
 
 protected void quit(){
  if(this.word!=null){
   this.word.invoke("Quit", new Variant[] {});
   this.word = null;
  }
 }
 
 public static void main(String[] args) {
 String templatef = "E://tempdoc//template1.doc";
  String outputf = "E://tempdoc//temp2.doc";
  try{
   //Declare an STA thread using ComThread.InitSTA() if all your method calls for that component are going to come from the same thread.
   ComThread.InitSTA();
   WordSpirit4J myword = new WordSpirit4J(templatef,outputf);
   myword.findAndReplace("old", "new", wdReplaceAll);
   myword.saveAsOutputFile();
   myword.closeTemplate();
   myword.quit();
   System.out.println("ok");
  }
  catch(FileNotFoundException e){
   e.printStackTrace();
  }
 finally{
 }
  ComThread.Release();//must
 }
}

 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章