一.需要有jacob的jar包支持

 import java.util.Iterator;
import java.util.List;
import java.util.HashMap; import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant; public class WordUtil {
private boolean saveOnExit; /**
* word文档
*/
private Dispatch doc = null; /**
* word运行程序对象
*/
private ActiveXComponent word; /**
* 所有word文档
*/
private Dispatch documents; /**
* 构造函数 */
public WordUtil() {
saveOnExit = false;
word = new ActiveXComponent("Word.Application");
word.setProperty("Visible", new Variant(false));
documents = word.getProperty("Documents").toDispatch();
} /**
* 设置参数:退出时是否保存
* @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.call(documents, "Open", inputDoc).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 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) {
// 移动到文件开头 moveStart(selection);
if (oldText.startsWith("table") || replaceObj instanceof List) {
replaceTable(selection, oldText, (List) replaceObj);
} else {
String newText = (String) replaceObj;
if (oldText.indexOf("image") != -1
|| newText.lastIndexOf(".bmp") != -1
|| newText.lastIndexOf(".jpg") != -1
|| newText.lastIndexOf(".gif") != -1)
while (find(selection, oldText)) {
replaceImage(selection, newText);
Dispatch.call(selection, "MoveRight");
}
else
while (find(selection, oldText)) {
replace(selection, newText);
Dispatch.call(selection, "MoveRight");
}
}
} /**
* 替换图片
* @param selection 图片的插入点
* @param imagePath 图片文件(全路径) */
public void replaceImage(Dispatch selection, String imagePath) {
Dispatch.call(Dispatch.get(selection, "InLineShapes").toDispatch(),
"AddPicture", imagePath);
} /**
* 替换表格
* @param selection 插入点 * @param tableName 表格名称,形如table$1@1、table$2@1...table$R@N,R代表从表格中的第N行开始填充,
* N代表word文件中的第N张表
* @param fields 表格中要替换的字段与数据的对应表
*/
public void replaceTable(Dispatch selection, String tableName, List dataList) {
if (dataList.size() <= 1) {
System.out.println("Empty table!");
return;
}
// 要填充的列 String[] cols = (String[]) dataList.get(0);
// 表格序号
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 = 1; i < dataList.size(); i++) {
// 某一行数据 String[] datas = (String[]) dataList.get(i);
// 在表格中添加一行 if (Dispatch.get(rows, "Count").getInt() < fromRow + i - 1)
Dispatch.call(rows, "Add");
// 填充该行的相关列
for (int j = 0; j < datas.length; j++) {
// 得到单元格 Dispatch cell = Dispatch.call(table, "Cell",
Integer.toString(fromRow + i - 1), cols[j])
.toDispatch();
// 选中单元格 Dispatch.call(cell, "Select");
// 设置格式
Dispatch font = Dispatch.get(selection, "Font").toDispatch();
Dispatch.put(font, "Bold", "0");
Dispatch.put(font, "Italic", "0");
// 输入数据
Dispatch.put(selection, "Text", datas[j]);
}
}
} /**
* 保存文件
* @param outputPath 输出文件(包含路径)
*/
public void save(String outputPath) {
Dispatch.call(Dispatch.call(word, "WordBasic").getDispatch(),
"FileSaveAs", outputPath);
} /**
* 关闭文件
* @param document 要关闭的文件
*/
public void close(Dispatch doc) {
Dispatch.call(doc, "Close", new Variant(saveOnExit));
} /**
* 退出程序 */
public void quit() {
word.invoke("Quit", new Variant[0]);
ComThread.Release();
} /**
* 根据模板、数据生成word文件
* @param inputPath 模板文件(包含路径)
* @param outPath 输出文件(包含路径)
* @param data 数据包(包含要填充的字段、对应的数据) */
public void toWord(String inputPath, String outPath, HashMap data) {
String oldText;
Object newValue;
try {
doc = open(inputPath);
Dispatch selection = select();
Iterator keys = data.keySet().iterator();
while (keys.hasNext()) {
oldText = (String) keys.next();
newValue = data.get(oldText);
replaceAll(selection, oldText, newValue);
}
save(outPath);
} catch (Exception e) {
//debug.println("toword[Java2Word]------------操作word文件失败!"+e.getMessage(),true); } finally {
if (doc != null)
close(doc);
}
} public static void main(String[] args) {
HashMap<String,String> data = new HashMap<String,String>();
data.put("$id$", "chec-001");
data.put("$name$", "合同1");
data.put("$sort$", "土建");
data.put("$pay$", "15");
data.put("$total$", "30");
WordUtil wordUtil = new WordUtil();
wordUtil.toWord("D:\\合同模板1.dot", "D:\\合同1.doc", data);
wordUtil = null;
}
}

Java操作Wrod文档的工具类的更多相关文章

  1. 使用Jacob操作Wrod文档的工具类代码

    一.需要有jacob的jar包支持 import java.util.Iterator; import java.util.List; import java.util.HashMap; import ...

  2. 读取EXCEL文档解析工具类

    package test;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException ...

  3. 【转载】Java Restful API 文档生成工具 smart-doc

    谁说生成api文档就必须要定义注解? 谁说生成接口请求和返回示例必须要在线? 用代码去探路,不断尝试更多文档交付的可能性. 如果代码有生命,为什么不换种方式和它对话! 一.背景 没有背景.就自己做自己 ...

  4. Java 的 Api 文档生成工具 JApiDocs 程序文档工具

    JApiDocs 详细介绍 简介 JApiDocs 是一个符合 Java 编程习惯的 Api 文档生成工具.最大程度地利用 Java 的语法特性,你只管用心设计好接口,添加必要的注释,JApiDocs ...

  5. java POI 导出到word文档 (附工具类)

    1,导入poi相关依赖 <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-o ...

  6. java操作csv文档通用工具类

    https://blog.csdn.net/rodge_rom/article/details/78898015 另: 参考该博主的关于FTP, EXCEL, WORD, 等工具类文章...

  7. Java操作word文档使用JACOB和POI操作word,Excel,PPT需要的jar包

    可参考文档: http://wibiline.iteye.com/blog/1725492 下载jar包 http://download.csdn.net/download/javashixiaofe ...

  8. C#XmlHelper操作Xml文档的帮助类

    using System.Xml; using System.Data; namespace DotNet.Utilities { /// <summary> /// Xml的操作公共类 ...

  9. [XML] C# XmlHelper操作Xml文档的帮助类 (转载)

    点击下载 XmlHelper.rar 主要功能如下所示 /// <summary> /// 类说明:XmlHelper /// 编 码 人:苏飞 /// 联系方式:361983679 // ...

随机推荐

  1. 【转】nginx的优缺点

    原博文出自于:http://blog.csdn.net/a454211787/article/details/22494485     感谢! 1.nginx相对于apache优点: 轻量级同样起we ...

  2. Spark生态之Spark Graphx

  3. FPGA静态时序分析——IO口时序(Input Delay /output Delay)

    1.1  概述 在高速系统中FPGA时序约束不止包括内部时钟约束,还应包括完整的IO时序约束和时序例外约束才能实现PCB板级的时序收敛.因此,FPGA时序约束中IO口时序约束也是一个重点.只有约束正确 ...

  4. TypeScript学习笔记(二):基本数据类型及数据转换

    数据类型 我们来看看TypeScript中的基本数据类型都有哪些. boolean 布尔值,支持true和false. var isDone: boolean = false; 默认为undefine ...

  5. C语言简单实现sizeof功能代码

    sizeof不是函数,而是运算符,C/C++语言编译器在预编译阶段的时候就已经处理完了sizeof的问题,也就是说sizeof类似于宏定义. 下面给出一个sizeof的一个宏定义实现版本 #defin ...

  6. 三、FreeMarker 模版开发指南 第三章 模版

    章节内容如下:   总体结构 指令 表达式 插值 一.总体结构 实际上你用程序语言编写的程序就是模板,模板也被称为FTL(代表FreeMarker模板语言).这是为编写模板设计的非常简单的编程语言. ...

  7. 根据条件自定义 cxGrid 的单元格样式

    当指定的单元格需要指定样式(如字体颜色设置为红色,背景色设置为黄色)时,可按如下步骤进行: 1.添加 csStyleRepository 控件,并新建 Style,设置前景(TextColor).背景 ...

  8. 从零开始学android开发-用Intent启动Activity的方法

    启动另外一个Activity,可以有的方法有用setClass()和Component Name 1. 先说在setClass启动一个Activity的方法吧: Intent intent = new ...

  9. Base64 图片转换工具

    以前在写asp的后台的时候,有一个上传功能是必须的,那时候进行的图片预览(未上传前)其实就是获取本地的图片路径来显示图片,但是随着HTML5的出现,可以把图片通过编码来实现预览. 在雅虎的36条速度优 ...

  10. delphi 为应用程序添加提示

    type  TForm1 = class(TForm)    Button1: TButton;    Panel1: TPanel;    Edit1: TEdit;    procedure Fo ...