package tansung.action;
import java.util.Map;
import com.jacob.activeX.*;import com.jacob.com.*;


public class WordBean extends java.awt.Panel {
// word文档 private Dispatch doc;
// word运行程序对象 private ActiveXComponent word;
// 所有word文档集合 private Dispatch documents;
private boolean saveOnExit = true;
public WordBean() { ComThread.InitSTA(); if (word == null) { word = new ActiveXComponent("Word.Application"); word.setProperty("Visible", new Variant(false)); } if (documents == null) documents = word.getProperty("Documents").toDispatch(); }
/* * 传入Map<string,string>数据类型,插入word标签 前一个string为标签,后一个为替换信息 */ public boolean insertBookMarkByInfo(Map<String, String> info, String fileName) throws Exception { try { openDocument(fileName); for (Map.Entry<String, String> temp : info.entrySet()) { if (!intoValueBookMark(temp.getKey(), temp.getValue())) return false; return true; } } catch (Exception e) { throw e; } return false; } /*************************************************************************** * 根据书签插入数据 * @param bookMarkKey *            书签名 * @param info *            插入的数据 * @return */
private boolean intoValueBookMark(String bookMarkKey, String info) throws Exception { if (word == null) word = new ActiveXComponent("Word.Application"); try { 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; } } catch (Exception e) { throw e; } return false; }
/** * 设置退出时参数 * @param saveOnExit *            boolean true-退出时保存文件,false-退出时不保存文件 */ public void setSaveOnExit(boolean saveOnExit) { this.saveOnExit = saveOnExit; }
/** * 打开一个已存在的文档 * @param docPath */ public void openDocument(String docPath) { closeDocument(); doc = Dispatch.call(documents, "Open", docPath).toDispatch(); }
/** * 文件保存或另存为 * 默认为我的文档 * @param savePath * 保存或另存为路径 */ public void save(String savePath) { Dispatch.call(doc, "SaveAs", 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; } documents = null; ComThread.Release(); }}

posted on 2011-05-01 16:24  xnfriday  阅读(1814)  评论(0编辑  收藏  举报