/*
jacob 相关包 官网下载
jacob 配置环境 http://xiaoduan.blog.51cto.com/502137/136692/ 调用其他控件需要到注册表注册 regsvr32 + 路径名+.dll文件( regsvr32 windows/system32/...dll)
jacob 详细解说 http://www.ltesting.net/ceshi/ruanjianceshikaifajishu/rjcskfyy/java/2007/0622/60996.html
jacob new Variant() 关于文档的保存格式 http://blog.sina.com.cn/s/blog_9276155f01017m5g.html
*/
package com.jacob.test;
扫描二维码关注公众号,回复:
4392840 查看本文章
![](/qrcode.jpg)
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
public class MSWordManager {
// word 文档
private Dispatch doc;
// word 运行程序对象
private ActiveXComponent word;
// word文档对象
private Dispatch documents;
// 选定的范围或插入点
private Dispatch selection;
private boolean saveOnExit = true;
public MSWordManager(boolean visible) {
if (word == null) {
// 初始化
// 创建调度对象基于word.Application
word = new ActiveXComponent(" Word.Application"); //已经安装word
word.setProperty("Visible", new Variant(visible));
}
if (documents == null)
documents = word.getProperty("Documents").toDispatch();
}
public void setSaveOnExit(boolean saveOnExit) {
this.saveOnExit = saveOnExit;
}
public void createNewDocument() {
doc = Dispatch.call(documents, "Add").toDispatch();
selection = Dispatch.get(word, "Selection").toDispatch();
}
public void insertText(String newText) {
Dispatch.put(selection, "Text", newText);
}
public void save(String savePath) {
Dispatch.call(
(Dispatch) Dispatch.call(word, "WordBasic").getDispatch(),
"FileSaveAs", savePath);
}
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;
}
public static void main(String[] args) {
MSWordManager ms=new MSWordManager(true);
ms.createNewDocument();
ms.insertText("hello song");
ms.save("d:\\1.doc");
ms.close();
ms.closeDocument();
}
}