https://blog.csdn.net/Fishroad/article/details/47951061?locationNum=2&fps=1

先下载jacob.jar包。解压后将jacob.dll放到windows/system32下面或\jre\bin下面。将jacob.jar加入项目。

这样项目的环境基本上搭建完成,接下来就是书写相关的代码:

/**
* 传入数据为HashMap对象,对象中的Key代表word模板中要替换的字段,Value代表用来替换的值。
* word模板中所有要替换的字段(即HashMap中的Key)以特殊字符开头和结尾,
* 如:$code$、$date$……,以免执行错误的替换。
* 所有要替换为图片的字段,Key中需包含image或者Value为图片的全路径
* (目前只判断文件后缀名为:.bmp、.jpg、.gif)。
* 要替换表格中的数据时,HashMap中的Key格式为“table$R@N”,其中:
* R代表从表格的第R行开始替换,N代表word模板中的第N张表格;
* Value为ArrayList对象,ArrayList中包含的对象统一为String[],一条String[]代表一行数据,
* ArrayList中第一条记录为特殊记录,记录的是表格中要替换的列号,
* 如:要替换第一列、第二列、第三列的数据,则第一条记录为String[3] {"1","2","3"}。
*/ import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator; import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant; /**
* 利用word模板生成word文件
* @typename:Java2word
* @author: FishRoad
* @since: 2015年8月24日 下午2:47:41
*
*/
public class Java2word { private boolean saveOnExit;
/**
* word文档
*/
Dispatch doc = null; /**
* word运行程序对象s
*/
private ActiveXComponent word;
/**
* 所有word文档
*/
private Dispatch documents; /**
* 构造函数
*/
public Java2word() {
if(word==null){
word = new ActiveXComponent("Word.Application");
word.setProperty("Visible",new Variant(false));
}
if(documents==null)
documents = word.getProperty("Documents").toDispatch();
saveOnExit = false;
} /**
* 设置参数:退出时是否保存
* @param saveOnExit boolean true-退出时保存文件,false-退出时不保存文件
*/
public void setSaveOnExit(boolean saveOnExit) {
this.saveOnExit = saveOnExit;
}
/**
* 得到参数:退出时是否保存
* @return boolean true-退出时保存文件,false-退出时不保存文件
*/
public boolean getSaveOnExit() {
return saveOnExit;
} /**
* 打开文件
* @param inputDoc String 要打开的文件,全路径
* @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 Dispatch 要移动的内容
* @param count int 移动的距离
*/
public void moveUp(Dispatch selection,int count) {
for(int i = 0;i < count;i ++)
Dispatch.call(selection,"MoveUp");
} /**
* 把选定内容或插入点向下移动
* @param selection Dispatch 要移动的内容
* @param count int 移动的距离
*/
public void moveDown(Dispatch selection,int count) {
for(int i = 0;i < count;i ++)
Dispatch.call(selection,"MoveDown");
} /**
* 把选定内容或插入点向左移动
* @param selection Dispatch 要移动的内容
* @param count int 移动的距离
*/
public void moveLeft(Dispatch selection,int count) {
for(int i = 0;i < count;i ++) {
Dispatch.call(selection,"MoveLeft");
}
} /**
* 把选定内容或插入点向右移动
* @param selection Dispatch 要移动的内容
* @param count int 移动的距离
*/
public void moveRight(Dispatch selection,int count) {
for(int i = 0;i < count;i ++)
Dispatch.call(selection,"MoveRight");
} /**
* 把插入点移动到文件首位置
* @param selection Dispatch 插入点
*/
public void moveStart(Dispatch selection) {
Dispatch.call(selection,"HomeKey",new Variant(6));
} /**
* 从选定内容或插入点开始查找文本
* @param selection Dispatch 选定内容
* @param toFindText String 要查找的文本
* @return boolean true-查找到并选中该文本,false-未查找到文本
*/
public boolean find(Dispatch selection,String toFindText) {
//从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 selection Dispatch 选定内容
* @param newText String 替换为文本
*/
public void replace(Dispatch selection,String newText) {
//设置替换文本
Dispatch.put(selection,"Text",newText);
} /**
* 全局替换
* @param selection Dispatch 选定内容或起始插入点
* @param oldText String 要替换的文本
* @param newText String 替换为文本
*/
public void replaceAll(Dispatch selection,String oldText,Object replaceObj) {
//移动到文件开头
moveStart(selection); if(oldText.startsWith("table") || replaceObj instanceof ArrayList)
replaceTable(selection,oldText,(ArrayList) replaceObj);
else {
String newText = (String) replaceObj;
if(newText==null)
newText="";
if(oldText.indexOf("image") != -1&!newText.trim().equals("") || 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 Dispatch 图片的插入点
* @param imagePath String 图片文件(全路径)
*/
public void replaceImage(Dispatch selection,String imagePath) {
Dispatch.call(Dispatch.get(selection,"InLineShapes").toDispatch(),"AddPicture",imagePath);
} /**
* 替换表格
* @param selection Dispatch 插入点
* @param tableName String 表格名称,
* 形如table$1@1、table$2@1...table$R@N,R代表从表格中的第N行开始填充,N代表word文件中的第N张表
* @param fields HashMap 表格中要替换的字段与数据的对应表
*/
public void replaceTable(Dispatch selection,String tableName,ArrayList 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 String 输出文件(包含路径)
*/
public void save(String outputPath) {
Dispatch.call(Dispatch.call(word,"WordBasic").getDispatch(),"FileSaveAs",outputPath);
} /**
* 关闭文件
* @param document Dispatch 要关闭的文件
*/
public void close(Dispatch doc) {
Dispatch.call(doc,"Close",new Variant(saveOnExit));
word.invoke("Quit",new Variant[]{});
word = null;
} /**
* 根据模板、数据生成word文件
* @param inputPath String 模板文件(包含路径)
* @param outPath String 输出文件(包含路径)
* @param data HashMap 数据包(包含要填充的字段、对应的数据)
*/
public void toWord(String inputPath,String outPath,HashMap data) {
String oldText;
Object newValue;
try {
if(doc==null)
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) {
System.out.println("操作word文件失败!");
e.printStackTrace();
} finally {
if(doc != null)
close(doc);
}
} public synchronized static void word(String inputPath,String outPath,HashMap data){
Java2word j2w = new Java2word();
j2w.toWord(inputPath,outPath,data);
} @SuppressWarnings({ "rawtypes", "unchecked" })
public static void main(String[] args) {
//替换word中相关的字段
HashMap data = new HashMap();
data.put("$reportDept$","2007-8-1");
data.put("$findDate$","2007-8-2");
data.put("$finder$","kdl");
data.put("$lineName$","5号线");
data.put("$voltageRate$","11月13日");
data.put("$towerNumberBound$","2004年11月10日");
data.put("$image1$","C:\\Users\\Administrator\\Pictures\\1.jpg");
data.put("$name$", "FishRoad");
data.put("$age$", "24");
//替换word中表格的数据
/**
* 要替换表格中的数据时,HashMap中的Key格式为“table$R@N”,其中:
* R代表从表格的第R行开始替换,N代表word模板中的第N张表格;
* Value为ArrayList对象,ArrayList中包含的对象统一为String[],
* 一条String[]代表一行数据,ArrayList中第一条记录为特殊记录,记录的是表格中要替换的列号,
* 如:要替换第一列、第二列、第三列的数据,则第一条记录为String[3] {"1","2","3"}
*/
ArrayList table1 = new ArrayList(3);
String[] fieldName1 = {"1","2","3"};
table1.add(fieldName1);
String[] field11 = {"1","751002","华夏证券"};
table1.add(field11);
String[] field21 = {"2","751004","国泰君安"};
table1.add(field21);
String[] field31 = {"3","751005","海通证券"};
table1.add(field31);
data.put("table$2@2",table1); Java2word j2w = new Java2word();
long time1 = System.currentTimeMillis();
j2w.toWord("E:/template.doc","E:/result.doc",data);
System.out.println("time cost : " + (System.currentTimeMillis() - time1));
}
} 以上是相关的代码,接下来就要配置word模板,如下:
导出的结果如下图:

利用模板导出文件(二)之jacob利用word模板导出word文件(Java2word)的更多相关文章

  1. NX二次开发-UFUN修改当前导出CGM文件选项设置UF_CGM_set_session_export_options

    文章转载自唐康林NX二次开发论坛,原文出处: http://www.nxopen.cn/thread-126-1-1.html 刚才有同学问到这个问题,如果是用NXOpen来做,直接录制一下就可以了: ...

  2. Spring MVC中使用POI导出Word

    内容绝大部分来源于网络 准备工作 准备[XwpfTUtil]工具类(来源于网络) 准备word模版 下载[XwpfTUtil]工具类 import org.apache.poi.xwpf.usermo ...

  3. poi导出word表格详解 超详细了

    转:非常感谢原作者 poi导出word表格详解 2018年07月20日 10:41:33 Z丶royAl 阅读数:36138   一.效果如下 二.js代码 function export_word( ...

  4. 无插件,无com组件,利用EXCEL、WORD模板做数据导出(一)

    本次随笔主要讲述着工作中是如何解决数据导出的,对于数据导出到excel在日常工作中大家还是比较常用的,那导出到word呢,改如何处理呢,简单的页面导出问题应该不大,但是如果是标准的公文导出呢,要保证其 ...

  5. 【3】利用Word模板生成文档的总结

    阅读目录 Word二次开发概况 使用DsoFramer进行开发 使用Interop进行开发 打开.关闭和写入操作 批量替换文本 遍历段落替换文本 查找后逐个替换文本 结论 在各类应用系统开发中,和Wo ...

  6. tp5 使用phpword 替换word模板并利用com组件转换pdf

    tp5   使用phpword 替换word模板并利用com组件转换pdf 一.首先composer安装PHPword,就不多说了 二.然后是把模板中要替换的部分用变量代替 三.把原始的模板文件放入项 ...

  7. JSP利用freemarker生成基于word模板的word文档

    利用freemarker生成基于word模板的word文档 freemarker简介 FreeMarker是一个用Java语言编写的模板引擎,它基于模板来生成文本输出.FreeMarker与Web容器 ...

  8. C# 利用WORD模板和标签(bookmark) 批量生成WORD

    前言: 由于对C#操作WORD不熟悉,也就留下这么一篇水文,别吐糟...=_=||| 利用Microsoft.Office.Interop.Word (2003版也就11版)——因为部分客户端还是用O ...

  9. 使用Spire.Doc组件利用模板导出Word文档

    以前一直是用Office的组件实现Word文档导出,但是让客户在服务器安装Office,涉及到版权:而且Office安装,包括权限配置也是比较麻烦. 现在流行使用第三方组件来实现对Office的操作, ...

随机推荐

  1. Windows下Apache服务器搭建

    Apache HTTP Server(简称Apache)是Apache软件基金会的一个开放源码的网页服务器,是世界使用排名第一的Web服务器软件,可以在大多数计算机操作系统中运行,由于其多平台和安全性 ...

  2. maven 打包不同环境

    支持不同环境打包 1 pom添加如下配置: 1)添加指定打包id 区分各个环境 <profiles> <profile> <id>dev</id> &l ...

  3. vue中eslintrc.js配置最详细介绍

    本文是对vue项目中自带文件eslintrc.js的内容解析, 介绍了各个eslint配置项的作用,以及为什么这样设置. 比较详细,看完能对eslint有较为全面的了解,基本解除对该文件的疑惑. /* ...

  4. Windows上安装运行hadoop

    0.自己编译安装步骤在这里,有英文版本连接:<英文传送门>. 自己编译尝试后不成功,换为下面使用别人编译好的版本的方法.参考博客:<初学hadoop,windows下安装> 1 ...

  5. idea javamaven项目 连接sqlserver 数据库方法

    这里用的是c3p0连接数据库 1.pom文件写法: <!-- 数据库连接池 --> <dependency> <groupId>com.mchange</gr ...

  6. 远程服务器返回了意外相应:(413) Request Entity Too Large。

    在从客户端向WCF服务端传送较大数据(>65535B)的时候,发现程序直接从Reference的BeginInvoke跳到EndInvoke,没有进入服务端的Service实际逻辑中,怀疑是由于 ...

  7. C# winform 窗体怎么隐藏标题栏,不显示标题栏

    //没有标题            this.FormBorderStyle = FormBorderStyle.None;            //任务栏不显示            this.S ...

  8. c++-pimer-plus-6th-chapter05

    Chapter Review 1 An entry-condition loop evaluates a test expression before entering the body of the ...

  9. Mysql更改表名大小写不敏感

    编辑配置文件 vi /etc/my.cnf 在[mysqld]后添加添加 lower_case_table_names=1 重启服务 service mysqld stop service mysql ...

  10. linux 下如何安装memcached 和启动服务

    一.安装gcc # yum -y install gcc 二.安装libevent # wget http://www.monkey.org/~provos/libevent-2.0.12-stabl ...