Package org.brain.tool

Source Code of org.brain.tool.Jacob2Word

package org.brain.tool;

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

public class Jacob2Word {
  // word文档
   private Dispatch doc;
   // word运行程序对象
   private ActiveXComponent word = null;
   // 所有word文档集合
   private Dispatch documents;
   // 选定的范围或插入点
   private Dispatch selection;
  
   private boolean saveOnExit = true;
   public Jacob2Word() {
    if (word == null) {
     word = new ActiveXComponent("Word.Application");
     word.setProperty("Visible", new Variant(false));
    }
    if (documents == null)
     documents = word.getProperty("Documents").toDispatch();
   }
   /**
    * 设置退出时参数
    *
    * @param saveOnExit
    *            boolean true-退出时保存文件,false-退出时不保存文件
    */
   public void setSaveOnExit(boolean saveOnExit) {
    this.saveOnExit = saveOnExit;
   }
   /**
    * 创建一个新的word文档
    *
    */
   public void createNewDocument() {
    doc = Dispatch.call(documents, "Add").toDispatch();
    selection = Dispatch.get(word, "Selection").toDispatch();
   }
  
   /**
    * 在当前插入点插入字符串
    *
    * @param newText
    *            要插入的新字符串
    */
   public void insertText(String newText) {
    Dispatch.put(selection, "Text", newText);
   }
  
   /**
    * 文件保存或另存为
    *
    * @param savePath
    *            保存或另存为路径
    */
   public void save(String savePath) {
    Dispatch.call(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;
   }

}
TOP

Related Classes of org.brain.tool.Jacob2Word

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.