Java根據word模板生成word文檔之後臺解析和實現及部分代碼(三)F

下面貼出對jacob進行簡單封裝類,暫時認爲應該是網絡上最全面的了,包括word打開,關閉,插入表格,替換表格,插入一個標籤,插入目錄等等,自己去找吧,或者自己去封裝一下。

下面我貼出全部代碼:

/**
 * /*************************************
 *
 *作用:利用JACOB插件根據word模板生成報告文件!
 *
 *說明:傳入數據爲HashMap對象,對象中的Key代表word模板中要替換的字段,Value代表用來替換的值。
 * 1.word模板中所有要替換的字段(即HashMap中的Key)以特殊字符開頭和結尾,如:$code$、$date$……,以免執行錯誤的替換。
 * 2.所有要替換爲圖片的字段,Key中需包含"image$xx"或者Value爲圖片的全路徑(目前只判斷文件後綴名爲:.bmp、.jpg、.gif)。
 * 3.要替換表格中的數據時,HashMap中的Key格式爲"table$R@N",其中:R代表從表格的第R行開始替換,N代表word模板中的第N張表格;
 * Value爲ArrayList對象,ArrayList中包含的對象統一爲String[],一條String[]代表一行數據,ArrayList中第一條記錄爲特殊記錄,
 * 4.記錄的是表格中要替換的列號,如:要替換第一列、第三列、第五列的數據,則第一條記錄爲String[3] {"1","3","5"}。
 * 5.表格標籤的定義形如:table$1@1、[email protected]$R@N,代表從第R個表格中的第N行開始填充,
 * word標籤的定義標籤爲: "soword$xx";
 * @author th
 * 
 *  /*************************************
 */
public class Export2WordService { 
	private static Logger logger = LoggerFactory.getLogger(Export2WordService.class);
	private boolean saveOnExit;
	
	/**
	* word文檔
	*/
	private Dispatch doc = null;

	/**
	* word運行程序對象
	*/
	private ActiveXComponent word;

	/**
	* 所有word文檔
	*/
	private Dispatch documents;
	
	
	 /**
	  *  選定的範圍或插入點
	  */
    private Dispatch selection;
    
    /** 
      * 表格中的所有列 
      */ 
     private  Dispatch columns;
     
     /** 
      * 表格中的某列 
      */ 
     private  Dispatch column;
     

	/**
	* 構造函數
	*/
	public Export2WordService() {
		try {
			   saveOnExit = false;
			   
			   System.out.println("創建線程開始...");
			   
			   ComThread.InitSTA();
			   
			   System.out.println("創建線程結束!");
			   
			   System.out.println("");
			   
			   System.out.println("創建Word.Application開始...");
			   
			   word = new ActiveXComponent("Word.Application");
			   
			   System.out.println("創建Word.Application結束!");
			   
			   Dispatch wordObject = word.getObject();
			   
			   Dispatch.put(wordObject, "Visible", new Variant(false));
			   
			   documents = word.getProperty("Documents").toDispatch();

		}catch (JacobException e) {
			logger.error("創建com的線程失敗....");
			e.printStackTrace();
		}catch (Exception e) {
			logger.error("創建com的線程失敗....");
			e.printStackTrace();
		}
	  
	}

    /**
    * 設置參數:退出時是否保存
    * 
    * @param saveOnExit
    *            true-退出時保存文件,false-退出時不保存文件
    */
    public void setSaveOnExit(boolean saveOnExit) {
       this.saveOnExit = saveOnExit;
    }

    /**
    * 得到參數:退出時是否保存
    * 
    * @return boolean true-退出時保存文件,false-退出時不保存文件
    */
    public boolean getSaveOnExit() {
       return saveOnExit;
    }

    /**
    * 打開文件
    * @param inputDoc 要打開的文件,全路徑
    * @return Dispatch 打開的文件
    */ 
    public Dispatch open(String inputDoc) {
//       return Dispatch.invoke(   
//                documents,   
//                "Open",   
//                Dispatch.Method,   
//                new Object[] {   
//                		inputDoc,     // 打開的文件路徑   
//                        new Variant(false),  //是否進行轉換 ConfirmConversions 否  
//                        new Variant(false)  //是否只讀   
//                }, new int[1]).toDispatch();    
    	return Dispatch.call(documents, "Open", inputDoc).toDispatch();
    }
    
    /**  
     * 打開一個保護文檔,  
     * @param docPath-文件全名  
     * @param pwd-密碼  
     */  
    public void openDocument(String docPath, String pwd)throws Exception {   
        closeDocument();           
        doc =  Dispatch.callN(documents, "Open", new Object[]{docPath, new Variant(false),    
                new Variant(false), new Variant(true), pwd}).toDispatch();   
        selection = Dispatch.get(word, "Selection").toDispatch();   
    }   


    /**
    * 選定內容
    * @return Dispatch 選定的範圍或插入點
    */
    public Dispatch select() {
       return word.getProperty("Selection").toDispatch();
    }

    /**
    * 把選定內容或插入點向上移動
    * 
    * @param selection 要移動的內容
    * @param count 移動的距離
    */
    public void moveUp(Dispatch selection, int count) {
       for (int i = 0; i < count; i++)
        Dispatch.call(selection, "MoveUp");
    }

    /**
    * 把選定內容或插入點向下移動
    * 
    * @param selection 要移動的內容
    * @param count  移動的距離
    */
    public void moveDown(Dispatch selection, int count) {
       for (int i = 0; i < count; i++)
        Dispatch.call(selection, "MoveDown");
    }

    /**
    * 把選定內容或插入點向左移動
    * 
    * @param selection 要移動的內容
    * @param count 移動的距離
    */
    public void moveLeft(Dispatch selection, int count) {
       for (int i = 0; i < count; i++)
        Dispatch.call(selection, "MoveLeft");
    }

    /**
    * 把選定內容或插入點向右移動
    * 
    * @param selection 要移動的內容
    * @param count 移動的距離
    */
    public void moveRight(Dispatch selection, int count) {
       for (int i = 0; i < count; i++)
        Dispatch.call(selection, "MoveRight");
    }

    /**
    * 把插入點移動到文件首位置
    * 
    * @param selection 插入點
    */
    public void moveStart(Dispatch selection) {
       Dispatch.call(selection, "HomeKey", new Variant(6));
    }
    
    /**
     * 增加縮進
    * @param pos
    *   縮進量
    */
   public void listIndent(int pos){
     Dispatch range = Dispatch.get(this.selection,"Range").toDispatch();
     Dispatch listFormat = Dispatch.get(range,"ListFormat").toDispatch();
     for (int i = 0; i < pos; i++)
        Dispatch.call(listFormat, "ListIndent");
    }
   
   
    /**
     * 減少縮進
    * @param pos
    *   縮進量
    */
   public void listOutdent(int pos){
     //Selection.Range.ListFormat.ListOutdent
    // Selection.Range.ListFormat.ListIndent
     Dispatch range = Dispatch.get(this.selection,"Range").toDispatch();
     Dispatch listFormat = Dispatch.get(range,"ListFormat").toDispatch();
     for (int i = 0; i < pos; i++)
        Dispatch.call(listFormat, "ListOutdent");
    }
   
   
   /**
    * 回車換行
    */
   public void enter(){
    Dispatch.call(this.selection,"TypeParagraph");
   }
   
   
   /**
    * 對當前selection設置項目符號和編號
    * @param tabIndex
    *     1: 項目編號
    *     2:編號
    *     3:多級編號
    *     4:列表樣式
    * @param index
    *     0:表示沒有 
    */
   public void applyListTemplate(int tabIndex,int index)
   {
     //取得ListGalleries對象列表
     Dispatch listGalleries = Dispatch.get(word, "ListGalleries").toDispatch();
     //取得列表中一個對象
     Dispatch listGallery = Dispatch.call(listGalleries, "Item", new Variant(tabIndex)).toDispatch();
     Dispatch listTemplates = Dispatch.get(listGallery, "ListTemplates").toDispatch();
     
     Dispatch range = Dispatch.get(this.selection, "Range").toDispatch();
     Dispatch listFormat = Dispatch.get(range, "ListFormat").toDispatch();
     Dispatch.call(listFormat, "ApplyListTemplate", Dispatch.call(listTemplates, "Item", new Variant(index)),new Variant(false),new Variant(0),new Variant(2));
   }
   
   
   
   /**
    * 插入標題
    * @param text
    * @param style
    *     設置標題的類型 "標題 1"
    */
   public void insertOutline(String text,String style)
   {
     this.enter();
     this.insertText(text);
    // this.moveLeft(text.length());
     //Dispatch.call(docStyles,"Add",new Variant("標題 1 Char"),new Variant(1));
     Dispatch.put(this.selection, "Style",getOutlineStyle(style));
     applyListTemplate(1,3);
     this.enter();
   }
   
   
   public  String getFileName(String docName){
    int pos = docName.lastIndexOf("\\");
    return docName.substring(pos+1);
   }

   
   /**
    * @param olePath
    */
   public Object insertOLE(String olePath) {
      Object ole = Dispatch.call(Dispatch.get(selection, "InLineShapes").toDispatch(),
        "AddOLEObject",  new Variant("Word.Document.8"), new Variant(olePath), new Variant(false), new Variant(true),
        new Variant("C:\\WINDOWS\\Installer\\{90110804-6000-11D3-8CFE-0150048383C9}\\wordicon.exe"),
         new Variant(1), new Variant(getFileName(olePath)));
    
      Dispatch.call(selection, "MoveRight");
      return ole;
   }
   
   
   public Object insertHyperlinks(){
    Dispatch Hyperlinks = Dispatch.get(this.doc, "Hyperlinks").toDispatch();
    Dispatch range = Dispatch.get(selection, "Range").toDispatch();
    return Dispatch.call(Hyperlinks,"Add",range, new Variant("Address"), 
            new Variant("SubAddress"), 
            new Variant("table.fieldName"),//建議的數據鏈接處
            new Variant("姓名"));

   }
   
   public com.jacob.com.Variant getOutlineStyle(String style){
    //取得word中所有的類型
    Dispatch docStyles = Dispatch.get(this.doc, "Styles").toDispatch();
    return Dispatch.call(docStyles, "Item", new Variant(style));
   }


   /**
    * 插入目錄
    */
   public void insertTablesOfContents(String pos) {
	    Dispatch tablesOfContents = Dispatch.get(this.doc, "TablesOfContents").toDispatch();
	    if (this.find(pos)) {
	    	  selection = select();
	          Dispatch textRange = Dispatch.get(selection, "Range").toDispatch();
	         // Dispatch.call(textRange, "Paste");
	          Dispatch.callN(tablesOfContents,"Add",new Object[]{textRange,new Variant(true),new Variant(1),
	        		    new Variant(3),new Variant(true), 
	        		    new Variant(true),new Variant(true)
	        		    ,new Variant("1"),new Variant(true),new Variant(true)});
//	          Dispatch.invoke(tablesOfContents,
//	      	        "Add", Dispatch.Method,new Object[]{textRange,new Variant(true),new Variant(1),
//	      	        new Variant(3),new Variant(true), 
//	      	        new Variant(true),new Variant(true)
//	      	        ,new Variant("1"),new Variant(true),new Variant(true)},new int[10]);
	      } 
   }




    /**
    * 從選定內容或插入點開始查找文本
    * 
    * @param selection
    *            選定內容
    * @param toFindText
    *            要查找的文本
    * @return boolean true-查找到並選中該文本,false-未查找到文本
    */
    public boolean find(Dispatch selection, String toFindText) {
       // 從selection所在位置開始查詢
       Dispatch find = Dispatch.call(selection, "Find").toDispatch();
       // 設置要查找的內容
       Dispatch.put(find, "Text", toFindText);
       // 向前查找
       Dispatch.put(find, "Forward", "True");
       // 設置格式
       Dispatch.put(find, "Format", "True");
       // 大小寫匹配
       Dispatch.put(find, "MatchCase", "True");
       // 全字匹配
       Dispatch.put(find, "MatchWholeWord", "True");
       // 查找並選中
       return Dispatch.call(find, "Execute").getBoolean();
    }

    /**
    * 把選定內容替換爲設定文本
    * 
    * @param selection
    *            選定內容
    * @param newText
    *            替換爲文本
    */
    public void replace(Dispatch selection, String newText) {
       // 設置替換文本
       Dispatch.put(selection, "Text", newText);
    }

    /**
    * 全局替換
    * 
    * @param selection
    *            選定內容或起始插入點
    * @param oldText
    *            要替換的文本
    * @param newText
    *            替換爲文本
    */
    public void replaceAll(Dispatch selection, String oldText, Object replaceObj) throws Exception{
//    	if(oldText.equals("table$1@38")){
//    		System.out.println("測試!");
//    	}
       // 移動到文件開頭
       moveStart(selection);
       if (oldText.startsWith("table") || replaceObj instanceof List<?>) {
    	   replaceTable(selection, oldText, (List<?>) replaceObj);
       }else if(oldText.startsWith("soword")){
    	   System.out.println("******************執行到    " + oldText + "  WORD書籤 替換..........");
    	   copyContentFromAnotherDoc(replaceObj.toString(),oldText);
       }else {
        String newText = (String) replaceObj;
        System.out.println("******************執行到    " + oldText + "  書籤 替換..........");
        if (oldText.toString().toLowerCase().indexOf("image") != -1
                || oldText.toString().toLowerCase().lastIndexOf(".bmp") != -1
                || oldText.toString().toLowerCase().lastIndexOf(".jpg") != -1
                || oldText.toString().toLowerCase().lastIndexOf(".gif") != -1
                || oldText.toString().toLowerCase().lastIndexOf(".jpeg") != -1
            	|| oldText.toString().toLowerCase().lastIndexOf(".png") != -1)
          while (find(selection, oldText)) {
           if(XmlPathDef.isExistFile(newText)){
	          	replaceImage(selection, newText);
	      	}else{
	      		Dispatch.put(selection, "Text", "文件不存在...");
	      	}
          Dispatch.call(selection, "MoveRight");
          
         }else
         while (find(selection, oldText)) {
          replace(selection, newText);
          Dispatch.call(selection, "MoveRight");
         }
        //System.out.println("替換值爲   " + replaceObj + "   成功! \n");
       }
    }

    /**
    * 替換圖片
    * 
    * @param selection 圖片的插入點
    * @param imagePath  圖片文件(全路徑)
    */
    public void replaceImage(Dispatch selection, String imagePath) throws Exception{
       Dispatch.call(Dispatch.get(selection, "InLineShapes").toDispatch(),
         "AddPicture", imagePath);
    }
    
   

    /**
    * 替換表格
    * 
    * @param selection 插入點
    * @param tableName 表格名稱,形如table$1@1、[email protected]$R@N,R代表從表格中的第N行開始填充,
    *            N代表word文件中的第N張表
    * @param fields 表格中要替換的字段與數據的對應表
    */
    public void replaceTable(Dispatch selection, String tableName, List<?> dataList) throws Exception {
    
       //用於測試   
	   if(tableName.equals("table$1@28")){
		   //System.out.println(tableName);
	   }
      if (dataList.size() <1) {
        System.out.println("Empty table!");
        return;
       }
       // 要填充的列
       System.out.println("******************開始執行" + tableName + " 表的替換....");
       // 表格序號
       String tbIndex = tableName.substring(tableName.lastIndexOf("@") + 1);
       // 從第幾行開始填充
       int fromRow = Integer.parseInt(tableName.substring(tableName.lastIndexOf("$") + 1, tableName.lastIndexOf("@")));
       // 所有表格
       Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();
       // 要填充的表格
       Dispatch table = Dispatch.call(tables, "Item", new Variant(tbIndex)).toDispatch();
       // 表格的所有行
       Dispatch rows = Dispatch.get(table, "Rows").toDispatch();
       // 填充表格
       
      
       for (int i = 0; i < dataList.size(); i++) { 
        // 某一行數據
        String[] datas = (String[]) dataList.get(i);
          if(datas != null && datas.length > 0){
        	// 在表格中添加一行
              if (Dispatch.get(rows, "Count").getInt() < fromRow + i){
               Dispatch.call(rows, "Add");
              }
              // 填充該行的相關列
	              for (int j = 1; j <= datas.length; j++) {
	               // 得到單元格
	               /**
	                * 參數 table 單元格 所選中的行 該行的單元序號
	                */
	               Dispatch cell = Dispatch.call(table, "Cell",new Variant(Integer.toString(fromRow + i)), new Variant(j)).toDispatch();
	               //System.out.println("******************數據庫中表數據有 "+ (dataList.size()-1) + " 行,模版表格有  " + datas.length + " 列,  執行到 : 第 " + i + " 行 , 第" + j + "列!");
	               // 選中單元格
	               Dispatch.call(cell, "Select");
	               // 設置格式
	               Dispatch font = Dispatch.get(selection, "Font").toDispatch();
	               Dispatch.put(font, "Bold", "0");
	               Dispatch.put(font, "Italic", "0");
	               // 輸入數據
	               if(CommonUtils.isNotNull(datas[j-1])){
	              	 if(datas[j-1].startsWith("soword")){
	                       //copyContentFromAnotherDoc(replaceObj.toString(),oldText);
	                      }else if (datas[j-1].toString().toLowerCase().indexOf("image") != -1
	                         || datas[j-1].toString().toLowerCase().lastIndexOf(".bmp") != -1
	                         || datas[j-1].toString().toLowerCase().lastIndexOf(".jpg") != -1
	                         || datas[j-1].toString().toLowerCase().lastIndexOf(".gif") != -1
	                         || datas[j-1].toString().toLowerCase().lastIndexOf(".jpeg") != -1
	                     	   || datas[j-1].toString().toLowerCase().lastIndexOf(".png") != -1){
	  	                        if(XmlPathDef.isExistFile(datas[j-1])){
	  	                        	replaceImage(selection, datas[j-1]);
	  	                    	}else{
	  	                    		Dispatch.put(selection, "Text", datas[j-1]);
	  	                    	}
	                        }else{
	                     	   if(datas[j-1].lastIndexOf(":") != -1 && datas[j-1].lastIndexOf(".") != -1 && XmlPathDef.isHave(datas[j-1],("/"))){
	                     		   Dispatch.put(selection, "Text", "無法顯示此文件...");
	                     	   }else{
	                     		   Dispatch.put(selection, "Text", datas[j-1]);
	                     	   }
	                          }
	  	              }else{
	  	            	 Dispatch.put(selection, "Text", "");
	  	            }
              }
            }
          }
         System.out.println("******************執行表的替換成功! \n");
    }

    /**
    * 關閉文件
    * 
    * @param document 要關閉的文件
    */
    public void close(Dispatch doc) {
       Dispatch.call(doc, "Close", new Variant(true));
    }

    /**
    * 退出程序
    */
    public void quit() {
       word.invoke("Quit", new Variant[0]);
       ComThread.Release();
    }
    
  
	 public void moveEnd() { 
	         if (doc == null) 
	            doc = Dispatch.get(word, "doc").toDispatch(); 
	 } 
	 
	 
	 /** 
	  * 創建表格 
	  *     
	  * @param pos    位置 
	  * @param cols 列數 
	  * @param rows 行數 
	  */ 
	 public void createTable(int numCols, int numRows){//(String pos, int numCols, int numRows) { 
         Dispatch tables = Dispatch.get(doc, "Tables").toDispatch(); 
         Dispatch range = Dispatch.get(doc, "Range").toDispatch(); 
         Dispatch newTable = Dispatch.call(tables, "Add", range, 
                         new Variant(numRows), new Variant(numCols)).toDispatch(); 
         Dispatch.call(doc, "MoveRight"); 
         moveEnd(); 
	 } 


 
	 /**
	 * 讀取文檔中第paragraphsIndex段文字的內容;
	 * @param paragraphsIndex
	 * @return
	 */
	 public String getParagraphs(int paragraphsIndex){
		 String ret = "";
		 Dispatch paragraphs = Dispatch.get(doc, "Paragraphs").toDispatch(); // 所有段落
		 int paragraphCount = Dispatch.get(paragraphs, "Count").getInt(); // 一共的段落數
		 Dispatch paragraph = null;
		 Dispatch range = null;
		 if(paragraphCount > paragraphsIndex && 0 < paragraphsIndex){ 
		 paragraph = Dispatch.call(paragraphs, "Item", new Variant(paragraphsIndex)).toDispatch();
		 range = Dispatch.get(paragraph, "Range").toDispatch();
		 ret = Dispatch.get(range, "Text").toString();
		 } 
		 return ret;
	
	 }
	    /**
	     * 
	     * @param visible 爲true表示word應用程序可見
	     */
	    public Export2WordService(boolean visible) {
	        if (word == null) {
	            word = new ActiveXComponent("Word.Application");
	            word.setProperty("Visible", new Variant(visible));
	        }
	        if (documents == null)
	            documents = word.getProperty("Documents").toDispatch();
	    }

	    /**
	     * 創建一個新的word文檔
	     * 
	     */
	    public void createNewDocument() {
	        doc = Dispatch.call(documents, "Add").toDispatch();
	        selection = Dispatch.get(word, "Selection").toDispatch();
	    }

	    /**
	     * 打開一個已存在的文檔
	     * 
	     * @param docPath
	     */
	    public void openDocument(String docPath) {
	        closeDocument();
	        doc = Dispatch.call(documents, "Open", docPath).toDispatch();
	        selection = Dispatch.get(word, "Selection").toDispatch();
	    }

	    /**
	     * 把選定的內容或插入點向上移動
	     * 
	     * @param pos 移動的距離
	     */
	    public void moveUp(int pos) {
	        if (selection == null)
	            selection = Dispatch.get(word, "Selection").toDispatch();
	        for (int i = 0; i < pos; i++)
	            Dispatch.call(selection, "MoveUp");

	    }

	    /**
	     * 把選定的內容或者插入點向下移動
	     * 
	     * @param pos 移動的距離
	     */
	    public void moveDown(int pos) {
	        if (selection == null)
	            selection = Dispatch.get(word, "Selection").toDispatch();
	        for (int i = 0; i < pos; i++)
	            Dispatch.call(selection, "MoveDown");
	    }

	    /**
	     * 把選定的內容或者插入點向左移動
	     * 
	     * @param pos 移動的距離
	     */
	    public void moveLeft(int pos) {
	        if (selection == null)
	            selection = Dispatch.get(word, "Selection").toDispatch();
	        for (int i = 0; i < pos; i++) {
	            Dispatch.call(selection, "MoveLeft");
	        }
	    }

	    /**
	     * 把選定的內容或者插入點向右移動
	     * 
	     * @param pos 移動的距離
	     */
	    public void moveRight(int pos) {
	        if (selection == null)
	            selection = Dispatch.get(word, "Selection").toDispatch();
	        for (int i = 0; i < pos; i++)
	            Dispatch.call(selection, "MoveRight");
	    }

	    /**
	     * 把插入點移動到文件首位置
	     * 
	     */
	    public void moveStart() {
	        if (selection == null)
	            selection = Dispatch.get(word, "Selection").toDispatch();
	        Dispatch.call(selection, "HomeKey", new Variant(6));
	    }

	    /**
	     * 從選定內容或插入點開始查找文本
	     * 
	     * @param toFindText 要查找的文本
	     * @return boolean true-查找到並選中該文本,false-未查找到文本
	     */
	    public boolean find(String toFindText) {
	        if (toFindText == null || toFindText.equals(""))
	            return false;
	        // 從selection所在位置開始查詢
	        Dispatch find = word.call(selection, "Find").toDispatch();
	        // 設置要查找的內容
	        Dispatch.put(find, "Text", toFindText);
	        // 向前查找
	        Dispatch.put(find, "Forward", "True");
	        // 設置格式
	        Dispatch.put(find, "Format", "True");
	        // 大小寫匹配
	        Dispatch.put(find, "MatchCase", "True");
	        // 全字匹配
	        Dispatch.put(find, "MatchWholeWord", "True");
	        // 查找並選中
	        return Dispatch.call(find, "Execute").getBoolean();
	    }

	    /**
	     * 把選定選定內容設定爲替換文本
	     * 
	     * @param toFindText 查找字符串
	     * @param newText 要替換的內容
	     * @return
	     */
	    public boolean replaceText(String toFindText, String newText) {
	        if (!find(toFindText))
	            return false;
	        Dispatch.put(selection, "Text", newText);
	        return true;
	    }

	    /**
	     * 全局替換文本
	     * 
	     * @param toFindText 查找字符串
	     * @param newText 要替換的內容
	     */
	    public void replaceAllText(String toFindText, String newText) {
	        while (find(toFindText)) {
	            Dispatch.put(selection, "Text", newText);
	            Dispatch.call(selection, "MoveRight");
	        }
	    }

	    /** 
	     * 在當前插入點插入字符串
	     * 
	     * @param newText 要插入的新字符串
	     */
	    public void insertText(String newText) {
	        Dispatch.put(selection, "Text", newText);
	    }

	    /** 
	     * 
	     * @param toFindText 要查找的字符串
	     * @param imagePath 圖片路徑
	     * @return
	     */
	    public boolean replaceImages(String toFindText, String imagePath) {
	        if (!find(toFindText)){
	        	 return false;
	        }else{
	        	File file = new File(imagePath);
		        if (file.exists()) {
		        	 Dispatch.call(Dispatch.get(selection, "InLineShapes").toDispatch(),
		 	                "AddPicture", imagePath);
		        }else{
		        	replace(selection, "");
		        }
	        }
	           
	        
	       
	        return true;
	    }

	    /**
	     * 全局替換圖片
	     * 
	     * @param toFindText 查找字符串
	     * @param imagePath 圖片路徑
	     */
	    public void replaceAllImage(String toFindText, String imagePath) {
	        while (find(toFindText)) {
	            Dispatch.call(Dispatch.get(selection, "InLineShapes").toDispatch(),
	                    "AddPicture", imagePath);
	            Dispatch.call(selection, "MoveRight");
	        }
	    }

	    /**
	     * 在當前插入點插入圖片
	     * 
	     * @param imagePath 圖片路徑
	     */
	    public void insertImage(String imagePath) {
	        Dispatch.call(Dispatch.get(selection, "InLineShapes").toDispatch(),
	                "AddPicture", imagePath);
	    }

	    /**
	     * 合併單元格
	     * 
	     * @param tableIndex
	     * @param fstCellRowIdx
	     * @param fstCellColIdx
	     * @param secCellRowIdx
	     * @param secCellColIdx
	     */
	    public void mergeCell(int tableIndex, int fstCellRowIdx, int fstCellColIdx,
	            int secCellRowIdx, int secCellColIdx) {
	        // 所有表格
	        Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();
	        // 要填充的表格
	        Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex))
	                .toDispatch();
	        Dispatch fstCell = Dispatch.call(table, "Cell",
	                new Variant(fstCellRowIdx), new Variant(fstCellColIdx))
	                .toDispatch();
	        Dispatch secCell = Dispatch.call(table, "Cell",
	                new Variant(secCellRowIdx), new Variant(secCellColIdx))
	                .toDispatch();
	        Dispatch.call(fstCell, "Merge", secCell);
	    }

	    /** 
	     * 在指定的單元格里填寫數據
	     * 
	     * @param tableIndex
	     * @param cellRowIdx
	     * @param cellColIdx
	     * @param txt
	     */
	    public void putTxtToCell(int tableIndex, int cellRowIdx, int cellColIdx,
	            String txt) {
	        // 所有表格
	        Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();
	        // 要填充的表格
	        Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex))
	                .toDispatch();
	        Dispatch cell = Dispatch.call(table, "Cell", new Variant(cellRowIdx),
	                new Variant(cellColIdx)).toDispatch();
	        Dispatch.call(cell, "Select");
	        Dispatch.put(selection, "Text", txt);
	    }

	    /**
	     * 在當前文檔拷貝數據
	     * 
	     * @param pos
	     */
	    public void copy(String toCopyText) {
	        moveStart();
	        if (this.find(toCopyText)) {
	            Dispatch textRange = Dispatch.get(selection, "Range").toDispatch();
	            Dispatch.call(textRange, "Copy");
	        }
	    }

	    /**
	     * 在當前文檔粘帖剪貼板數據
	     * 
	     * @param pos
	     */
	    public void paste(String pos) {
	        moveStart();
	        if (this.find(pos)) {
	            Dispatch textRange = Dispatch.get(selection, "Range").toDispatch();
	            Dispatch.call(textRange, "Paste");
	        }
	    }

	    /**
	     * 在當前文檔指定的位置拷貝表格
	     * 
	     * @param pos 當前文檔指定的位置
	     * @param tableIndex 被拷貝的表格在word文檔中所處的位置
	     */
	    public void copyTable(String pos, int tableIndex) {
	        Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();
	        Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex))
	                .toDispatch();
	        Dispatch range = Dispatch.get(table, "Range").toDispatch();
	        Dispatch.call(range, "Copy");
	        if (this.find(pos)) {
	            Dispatch textRange = Dispatch.get(selection, "Range").toDispatch();
	            Dispatch.call(textRange, "Paste");
	        }
	    }

	    /**
	     * 在當前文檔末尾拷貝來自另一個文檔中的段落
	     * 
	     * @param anotherDocPath 另一個文檔的磁盤路徑
	     * @param tableIndex 被拷貝的段落在另一格文檔中的序號(從1開始)
	     */
	    public void copyParagraphFromAnotherDoc(String anotherDocPath,
	            int paragraphIndex) {
	        Dispatch wordContent = Dispatch.get(doc, "Content").toDispatch(); // 取得當前文檔的內容
	        Dispatch.call(wordContent, "InsertAfter", "$selection$");// 插入特殊符定位插入點
	        copyParagraphFromAnotherDoc(anotherDocPath, paragraphIndex,
	                "$selection$");
	    }

	    /**
	     * 在當前文檔指定的位置拷貝來自另一個文檔中的段落
	     * 
	     * @param anotherDocPath 另一個文檔的磁盤路徑
	     * @param tableIndex 被拷貝的段落在另一格文檔中的序號(從1開始)
	     * @param pos 當前文檔指定的位置
	     */
	    public void copyParagraphFromAnotherDoc(String anotherDocPath,
	            int paragraphIndex, String pos) {
	        Dispatch doc2 = null;
	        try {
	            doc2 = Dispatch.call(documents, "Open", anotherDocPath)
	                    .toDispatch();
	            Dispatch paragraphs = Dispatch.get(doc2, "Paragraphs").toDispatch();

	            Dispatch paragraph = Dispatch.call(paragraphs, "Item",
	                    new Variant(paragraphIndex)).toDispatch();
	            Dispatch range = Dispatch.get(paragraph, "Range").toDispatch();
	            Dispatch.call(range, "Copy");
	            if (this.find(pos)) {
	                Dispatch textRange = Dispatch.get(selection, "Range")
	                        .toDispatch();
	                Dispatch.call(textRange, "Paste");
	            }
	        } catch (Exception e) {
	            e.printStackTrace();
	        } finally {
	            if (doc2 != null) {
	                Dispatch.call(doc2, "Close", new Variant(saveOnExit));
	                doc2 = null;
	            }
	        }
	    }

	    /**
	     * 在當前文檔指定的位置拷貝來自另一個文檔中的表格
	     * 
	     * @param anotherDocPath 另一個文檔的磁盤路徑
	     * @param tableIndex 被拷貝的表格在另一格文檔中的序號(從1開始)
	     * @param pos 當前文檔指定的位置
	     */
	    public void copyTableFromAnotherDoc(String anotherDocPath, int tableIndex,
	            String pos) {
	        Dispatch doc2 = null;
	        try {
	            doc2 = Dispatch.call(documents, "Open", anotherDocPath)
	                    .toDispatch();
	            Dispatch tables = Dispatch.get(doc2, "Tables").toDispatch();
	            Dispatch table = Dispatch.call(tables, "Item",
	                    new Variant(tableIndex)).toDispatch();
	            Dispatch range = Dispatch.get(table, "Range").toDispatch();
	            Dispatch.call(range, "Copy");
	            if (this.find(pos)) {
	                Dispatch textRange = Dispatch.get(selection, "Range")
	                        .toDispatch();
	                Dispatch.call(textRange, "Paste");
	            }
	        } catch (Exception e) {
	            e.printStackTrace();
	        } finally {
	            if (doc2 != null) {
	                Dispatch.call(doc2, "Close", new Variant(saveOnExit));
	                doc2 = null;
	            }
	        }
	    }

	    /**
	     * 在當前文檔指定的位置拷貝來自另一個文檔中的圖片
	     * 
	     * @param anotherDocPath 另一個文檔的磁盤路徑
	     * @param shapeIndex 被拷貝的圖片在另一格文檔中的位置
	     * @param pos 當前文檔指定的位置
	     */
	    public void copyImageFromAnotherDoc(String anotherDocPath, int shapeIndex,
	            String pos) {
	        Dispatch doc2 = null;
	        try {
	            doc2 = Dispatch.call(documents, "Open", anotherDocPath)
	                    .toDispatch();
	            Dispatch shapes = Dispatch.get(doc2, "InLineShapes").toDispatch();
	            Dispatch shape = Dispatch.call(shapes, "Item",
	                    new Variant(shapeIndex)).toDispatch();
	            Dispatch imageRange = Dispatch.get(shape, "Range").toDispatch();
	            Dispatch.call(imageRange, "Copy");
	            if (this.find(pos)) {
	                Dispatch textRange = Dispatch.get(selection, "Range")
	                        .toDispatch();
	                Dispatch.call(textRange, "Paste");
	            }
	        } catch (Exception e) {
	            e.printStackTrace();
	        } finally {
	            if (doc2 != null) {
	                Dispatch.call(doc2, "Close", new Variant(saveOnExit));
	                doc2 = null;
	            }
	        }
	    }
	    
	    
	    /**
	    * 在當前文檔末尾拷貝另一個文檔的所有內容
	    */
	    public void copyContentFromAnotherDoc(String anotherDocPath) {
	       try {
		       Dispatch wordContent = Dispatch.get(doc, "Content").toDispatch(); // 取得當前文檔的內容
		       Dispatch.call(wordContent, "InsertAfter", "$selection$");// 插入特殊符定位插入點
		       copyContentFromAnotherDoc(anotherDocPath, "$selection$");
		       this.moveEnd();
		       this.moveUp(1);
		       //Dispatch.call(wordContent, "InsertAfter", "$selection$");// 插入特殊符定位插入點
		       Dispatch.put(selection, "Text", "$selection$");
		       copyContentFromAnotherDoc(anotherDocPath, "$selection$");
		        //Dispatch.call(wordContent, "Delete").toDispatch();
			} catch (Exception e) {
				 e.printStackTrace();
			}
	    }

	    
	    /**
	    * 拷貝另個文檔的所有內容
	    * @param pos 當前文檔指定的位置
	    */
	    public void copyContentFromAnotherDoc(String anotherDocPath, String pos) {
	       Dispatch doc2 = null;
	       try {
	        doc2 = Dispatch.call(documents, "Open", anotherDocPath).toDispatch();
	        if(doc2 != null && !doc2.equals("")){
	        	 Dispatch content = Dispatch.get(doc2, "Content").toDispatch();
	 	         Dispatch.call(content, "Copy");
	 	         if (this.find(pos)) {
	 	          Dispatch textRange = Dispatch.get(selection, "Range").toDispatch();
	 	          Dispatch.call(textRange, "Paste");
	 	        }
	         }else{
	        	 replace(selection, "");
	         }
	       } catch (Exception e) {
	          e.printStackTrace();
	       } finally {
	          if (doc2 != null) {
		         Dispatch.call(doc2, "Close", new Variant(saveOnExit));
		         doc2 = null;
	        }
	       }
	    }



	    /**
	     * 創建表格
	     * 
	     * @param pos  位置
	     * @param cols 列數
	     * @param rows 行數
	     */
	    public void createTable(String pos, int numCols, int numRows) {
	        if (find(pos)) {
	            Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();
	            Dispatch range = Dispatch.get(selection, "Range").toDispatch();
	            Dispatch newTable = Dispatch.call(tables, "Add", range,new Variant(numRows), new Variant(numCols),new Variant(1)).toDispatch();
	            Dispatch.call(selection, "MoveRight");
	        }
	    }
	    
	    
	    /**
	     * 獲取某個表格的所有行
	     * 
	     * @param tableIndex word文件中的第N張表(從1開始)
	     */
	    public Variant getTableAllRowNum(int tableIndex) {
	        // 所有表格
	        Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();
	        // 要填充的表格
	        Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex))
	                .toDispatch();
	        // 表格的所有行
	        Dispatch rows = Dispatch.get(table, "Rows").toDispatch();
	        System.out.println("表格的總行數爲:" + Dispatch.get(rows, "Count"));  
	        return Dispatch.get(rows, "Count");
	    }
	    
	    
	    /**
	     * 獲取某個表格的所有行
	     * 
	     * @param tableIndex word文檔中的第N張表(從1開始)
	     */
	    public Variant getTableAllColNum(int tableIndex) {
	        // 所有表格
	        Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();
	        // 要填充的表格
	        Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex))
	                .toDispatch();
	        // 表格的所有列
	        Dispatch cols = Dispatch.get(table, "Columns").toDispatch();
	        System.out.println(Dispatch.get(cols, "Count"));
	        return Dispatch.get(cols, "Count");
	    }


	    /**
	     * 在指定行前面增加行
	     * 
	     * @param tableIndex word文件中的第N張表(從1開始)
	     * @param rowIndex 指定行的序號(從1開始)
	     */
	    public void addTableRow(int tableIndex, int rowIndex) {
	        // 所有表格
	        Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();
	        // 要填充的表格
	        Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex))
	                .toDispatch();
	        // 表格的所有行
	        Dispatch rows = Dispatch.get(table, "Rows").toDispatch();
	        Dispatch row = Dispatch.call(rows, "Item", new Variant(rowIndex))
	                .toDispatch();
	        Dispatch.call(rows, "Add", new Variant(row));
	    }
	    

	    /**
	     * 在第1行前增加一行
	     * 
	     * @param tableIndex word文檔中的第N張表(從1開始)
	     */
	    public void addFirstTableRow(int tableIndex) {
	        // 所有表格
	        Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();
	        // 要填充的表格
	        Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex))
	                .toDispatch();
	        // 表格的所有行
	        Dispatch rows = Dispatch.get(table, "Rows").toDispatch();
	        Dispatch row = Dispatch.get(rows, "First").toDispatch();
	        Dispatch.call(rows, "Add", new Variant(row));
	    }
	    

	    /**
	     * 在最後1行前增加一行
	     * 
	     * @param tableIndex word文檔中的第N張表(從1開始)
	     */
	    public void addLastTableRow(int tableIndex) {
	        // 所有表格
	        Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();
	        // 要填充的表格
	        Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex))
	                .toDispatch();
	        // 表格的所有行
	        Dispatch rows = Dispatch.get(table, "Rows").toDispatch();
	        Dispatch row = Dispatch.get(rows, "Last").toDispatch();
	        Dispatch.call(rows, "Add", new Variant(row));
	    }

	    
	    /**
	     * 增加一行(在最後面添加一行)
	     * 
	     * @param tableIndex word文檔中的第N張表(從1開始)
	     */
	    public void addRow(int tableIndex) {
	        Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();
	        // 要填充的表格
	        Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex))
	                .toDispatch();
	        // 表格的所有行
	        Dispatch rows = Dispatch.get(table, "Rows").toDispatch();
	        Dispatch.call(rows, "Add");
	    }

	    
	    /**
	     * 增加一列(在最後面添加一列)
	     * 
	     * @param tableIndex word文檔中的第N張表(從1開始)
	     */
	    public void addCol(int tableIndex) {
	        // 所有表格
	        Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();
	        // 要填充的表格
	        Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex))
	                .toDispatch();
	        // 表格的所有行
	        Dispatch cols = Dispatch.get(table, "Columns").toDispatch();
	        Dispatch.call(cols, "Add").toDispatch();
	        Dispatch.call(cols, "AutoFit");
	    }

	    
	    /**
	     * 在指定列前面增加表格的列
	     * 
	     * @param tableIndex word文檔中的第N張表(從1開始)
	     * @param colIndex  指定列的序號 (從1開始)
	     */
	    public void addTableCol(int tableIndex, int colIndex) {
	        // 所有表格
	        Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();
	        // 要填充的表格
	        Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex))
	                .toDispatch();
	        // 表格的所有列
	        Dispatch cols = Dispatch.get(table, "Columns").toDispatch();
	        System.out.println(Dispatch.get(cols, "Count"));
	        Dispatch col = Dispatch.call(cols, "Item", new Variant(colIndex))
	                .toDispatch();
	        // Dispatch col = Dispatch.get(cols, "First").toDispatch();
	        Dispatch.call(cols, "Add", col).toDispatch();
	        Dispatch.call(cols, "AutoFit");
	    }
	    

	    /**
	     * 在第1列前增加一列
	     * 
	     * @param tableIndex word文檔中的第N張表(從1開始)
	     */
	    public void addFirstTableCol(int tableIndex) {
	        Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();
	        // 要填充的表格
	        Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex))
	                .toDispatch();
	        // 表格的所有行
	        Dispatch cols = Dispatch.get(table, "Columns").toDispatch();
	        Dispatch col = Dispatch.get(cols, "First").toDispatch();
	        Dispatch.call(cols, "Add", col).toDispatch();
	        Dispatch.call(cols, "AutoFit");
	    }

	    
	    /**
	     * 在最後一列前增加一列
	     * 
	     * @param tableIndex word文檔中的第N張表(從1開始)
	     */
	    public void addLastTableCol(int tableIndex) {
	        Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();
	        // 要填充的表格
	        Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex))
	                .toDispatch();
	        // 表格的所有行
	        Dispatch cols = Dispatch.get(table, "Columns").toDispatch();
	        Dispatch col = Dispatch.get(cols, "Last").toDispatch();
	        Dispatch.call(cols, "Add", col).toDispatch();
	        Dispatch.call(cols, "AutoFit");
	    }

	    /**
	     * 自動調整表格
	     */
	    public void autoFitTable() {
	        Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();
	        int count = Dispatch.get(tables, "Count").toInt();
	        for (int i = 0; i < count; i++) {
	            Dispatch table = Dispatch.call(tables, "Item", new Variant(i + 1))
	                    .toDispatch();
	            Dispatch cols = Dispatch.get(table, "Columns").toDispatch();
	            Dispatch.call(cols, "AutoFit");
	        }
	    }
	    

	    /**
	     * 調用word裏的宏以調整表格的寬度,其中宏保存在document下
	     * 
	     */
	    @SuppressWarnings("deprecation")
		public void callWordMacro() {
	        Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();
	        int count = Dispatch.get(tables, "Count").toInt();
	        Variant vMacroName = new Variant("Normal.NewMacros.tableFit");
	        @SuppressWarnings("unused")
			Variant vParam = new Variant("param1");
	        Variant para[] = new Variant[] { vMacroName };
	        for (int i = 0; i < para.length; i++) {
	            Dispatch table = Dispatch.call(tables, "Item", new Variant(i + 1))
	                    .toDispatch();
	            Dispatch.call(table, "Select");
	            Dispatch.call(word, "Run", "tableFitContent");
	        }
	    }

	    /**
	     * 設置當前選定內容的字體
	     * 
	     * @param boldSize
	     * @param italicSize
	     * @param underLineSize 下劃線
	     * @param colorSize 字體顏色
	     * @param size 字體大小
	     * @param name 字體名稱
	     */
	    public void setFont(boolean bold, boolean italic, boolean underLine,
	            String colorSize, String size, String name) {
	        Dispatch font = Dispatch.get(selection, "Font").toDispatch();
	        Dispatch.put(font, "Name", new Variant(name));
	        Dispatch.put(font, "Bold", new Variant(bold));
	        Dispatch.put(font, "Italic", new Variant(italic));
	        Dispatch.put(font, "Underline", new Variant(underLine));
	        Dispatch.put(font, "Color", colorSize);
	        Dispatch.put(font, "Size", size);
	    }

	       /** 
	         * 設置指定表格指定列的背景色 
	         *  
	         * @param tableIndex 
	         * @param columnIndex 
	        * @param color  取值範圍 0 < color < 17 默認:16 淺灰色 1:黑色 2:藍色 3:淺藍 ............... 
	         */ 
	     public  void  setColumnBgColor( int  tableIndex,  int  columnIndex,  int  color) { 
	             this.getTable(tableIndex); 
	             this.setColumnBgColor(columnIndex, color); 
	        } 
	    
	     
	     
	         /** 
	         * 設置當前表格指定列的背景色 
	         *  
	         * @param columnIndex 
	         * @param color  取值範圍 0 < color < 17 默認:16 淺灰色 1:黑色 2:藍色 3:淺藍 ............... 
	         */ 
	         public   void  setColumnBgColor( int  columnIndex,  int  color) { 
	             this.getColumn(columnIndex); 
	            Dispatch shading = Dispatch.get(column,  "Shading" ).toDispatch();
	             if (color >  16  || color <  1 ) 
	                color =  16 ; 
	             	Dispatch.put(shading,  "BackgroundPatternColorIndex" ,  new  Variant(color)); 
	        } 
	         
	         
	         /** 
	              * 得到當前表格的某一列 
	              *  
	              * @param index 
	              *            列索引 
	              * @return 
	              */ 
	              public  Dispatch getColumn( int  columnIndex) { 
	                  if  (columns ==  null ) 
	                      this.getColumns(); 
	                  return   this.column = Dispatch.call(columns,  "Item" , 
	                          new  Variant(columnIndex)).toDispatch(); 
	             } 
	         
	         /** 
	              * 得到指定表格的多有列 
	              *  
	              * @param tableIndex 
	              * @return 
	              */ 
	              public  Dispatch getColumns( int  tableIndex) { 
	                 getTable(tableIndex); 
	         
	                  return   this.getColumns(); 
	             } 
	   
	              /** 
	                   * 得到當前表格的所有的列 
	                   *  
	                   * @return 
	                   */ 
	                   // 需要找到Dispatch對象,這裏的Variant(1)不行一定要做成變量 
	                public  Dispatch getColumns() { 
	                       // this.getTables(); 
	                      Dispatch tables = Dispatch.get(doc,  "Tables" ).toDispatch(); 
	                      Dispatch table = Dispatch.call(tables,  "Item" ,  new  Variant( 1 )) 
	                              .toDispatch(); 
	                       return   this .columns = Dispatch.get(table,  "Columns" ).toDispatch(); 
	                  } 
	              
	            /** 
	              * 查找表 
	              *  
	              * @param tableIndex 
	              * @return 
	              */ 
	          public  Dispatch getTable( int  tableIndex) { 
	                 Dispatch tables = Dispatch.get(doc,  "Tables" ).toDispatch(); 
	                 Dispatch table = Dispatch.call(tables,  "Item" ,  new  Variant(tableIndex)) 
	                         .toDispatch(); 
	        
	                  return  table; 
	             } 
	    
	       
	    /**  
	     * 保護當前檔,如果不存在, 使用expression.Protect(Type, NoReset, Password)  
	     *   
	     * @param pwd  
	     * WdProtectionType 可以是下列 WdProtectionType 常量之一:   
	     *      1-wdAllowOnlyComments, 2-wdAllowOnlyFormFields, 0-wdAllowOnlyRevisions,   
	     *      -1-wdNoProtection, 3-wdAllowOnlyReading  
	     *   
	     * 使用參照 main1()  
	     */  
	    public void protectedWord(String pwd){   
	        String protectionType = Dispatch.get(doc, "ProtectionType").toString();   
	        if(protectionType.equals("-1")){       
	            Dispatch.call(doc, "Protect", new Variant(3), new Variant(true), pwd);   
	        }      
	    }   
	       
	    /**  
	     * 解除文檔保護,如果存在  
	     * @param pwd  
	     * WdProtectionType 常量之一(Long 類型,只讀):  
	     *      1-wdAllowOnlyComments,2-wdAllowOnlyFormFields、  
	     *      0-wdAllowOnlyRevisions,-1-wdNoProtection, 3-wdAllowOnlyReading  
	     *   
	     *      使用參照 main1()  
	     */  
	    public void unProtectedWord(String pwd){   
	        String protectionType = Dispatch.get(doc, "ProtectionType").toString();   
	        if(protectionType.equals("3")){    
	            Dispatch.call(doc, "Unprotect", pwd);   
	        }   
	    }   
	       
	    /**  
	     * 設置word文檔安全級別  
	     * @param value  
	     *      1-msoAutomationSecurityByUI  使用“安全”對話框指定的安全設置。  
	     *      2-msoAutomationSecurityForceDisable  在程序打開的所有文件中禁用所有宏,而不顯示任何安全提醒。  
	     *      3-msoAutomationSecurityLow  啓用所有宏,這是啓動應用程序時的默認值。  
	     */  
	    public void setAutomationSecurity(int value){   
	        word.setProperty("AutomationSecurity", new Variant(value));    
	    }   
	    
	       
	    /**  
	     * 設置頁眉文字  
	     * @param cont  
	     * @return  
	     *   
	     * Sub AddHeaderText()  
	     * '設置頁眉或頁腳中的文字  
	     * '由 Headers、Footers 和 HeaderFooter 屬性返回 HeaderFooter 對象。下列示例更改當前頁眉中的文字。  
	     *  With ActiveDocument.ActiveWindow.View  
	     *      .SeekView = wdSeekCurrentPageHeader  
	     *      Selection.HeaderFooter.Range.Text = "Header text"  
	     *      .SeekView = wdSeekMainDocument  
	     *  End With  
	     * End Sub  
	     */  
	    public void setHeaderContent(String cont){   
	        Dispatch activeWindow = Dispatch.get(doc, "ActiveWindow").toDispatch();   
	        Dispatch view = Dispatch.get(activeWindow, "View").toDispatch();   
	        //Dispatch seekView = Dispatch.get(view, "SeekView").toDispatch();   
	        Dispatch.put(view, "SeekView", new Variant(9));         //wdSeekCurrentPageHeader-9   
	           
	        Dispatch headerFooter = Dispatch.get(selection, "HeaderFooter").toDispatch();   
	        Dispatch range = Dispatch.get(headerFooter, "Range").toDispatch();   
	        Dispatch.put(range, "Text", new Variant(cont));    
	        //String content = Dispatch.get(range, "Text").toString();   
	        Dispatch font = Dispatch.get(range, "Font").toDispatch();   
	           
	        Dispatch.put(font, "Name", new Variant("楷體_GB2312"));   
	        Dispatch.put(font, "Bold", new Variant(true));   
	        //Dispatch.put(font, "Italic", new Variant(true));   
	        //Dispatch.put(font, "Underline", new Variant(true));   
	        Dispatch.put(font, "Size", 9);   
	           
	        Dispatch.put(view, "SeekView", new Variant(0));         //wdSeekMainDocument-0恢復視圖;   
	    }  

	    
	    /***************************************************************************
	     * 刪除書籤
	     * 
	     * @param mark  書籤名
	     * @param info  可替換
	     * @return
	     */
	    public boolean deleteBookMark(String markKey, String info) throws Exception{
	        Dispatch activeDocument = word.getProperty("ActiveDocument").toDispatch();
	        Dispatch bookMarks = word.call(activeDocument, "Bookmarks").toDispatch();
	        boolean isExists = word.call(bookMarks, "Exists", markKey).toBoolean();
	        if (isExists) {
	            Dispatch n = Dispatch.call(bookMarks, "Item", markKey).toDispatch();
	            Dispatch.call(n, "Delete");
	            return true;
	        } 
	        return false;
	    }
	    
	/***************************************************************************
	     * 根據書籤插入數據
	     * 
	     * @param bookMarkKey 書籤名
	     * @param info  插入的數據
	     * @return
	     */
	  
	    public boolean intoValueBookMark(String bookMarkKey, String info) throws Exception{
	        Dispatch activeDocument = word.getProperty("ActiveDocument").toDispatch();
	        Dispatch bookMarks = word.call(activeDocument, "Bookmarks").toDispatch();
	        boolean bookMarkExist = word.call(bookMarks, "Exists", bookMarkKey).toBoolean();
	        if (bookMarkExist) {
	            Dispatch rangeItem = Dispatch.call(bookMarks, "Item", bookMarkKey).toDispatch();
	            Dispatch range = Dispatch.call(rangeItem, "Range").toDispatch();
	            Dispatch.put(range, "Text", new Variant(info));
	            return true;
	        } 
	        return false;
	    }

	    /**
	     * 文件保存或另存爲
	     * 
	     * @param savePath 保存或另存爲路徑
	     */
	    public void save(String savePath) {
	        Dispatch.call(
	                (Dispatch) Dispatch.call(word, "WordBasic").getDispatch(),"FileSaveAs", savePath);
	    }

	    /**
	     * 關閉當前word文檔
	     * 
	     */
	    public void closeDocument() {
	        if (doc != null) {
	            Dispatch.call(doc, "Save");
	            Dispatch.call(doc, "Close", new Variant(saveOnExit));
	            doc = null;
	        }
	    }

	    /**
	     * 關閉全部應用
	     * 
	     */
	    public void close() {
	        closeDocument();
	        if (word != null) {
	            Dispatch.call(word, "Quit");
	            word = null;
	        }
	        selection = null;
	        documents = null;
	    }

	    /**
	     * 打印當前word文檔
	     * 
	     */
	    public void printFile() {
	        if (doc != null) {
	            Dispatch.call(doc, "PrintOut");
	        }
	    }

有了這個工具類之後 就是自己去調用它的方法了,很全我說了,需要認真去閱讀,找其中的方法就ok了!


未完待續

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