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

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

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

  1. /**
  2. * 传入数据为HashMap对象,对象中的Key代表word模板中要替换的字段,Value代表用来替换的值。
  3. * word模板中所有要替换的字段(即HashMap中的Key)以特殊字符开头和结尾,
  4. * 如:$code$、$date$……,以免执行错误的替换。
  5. * 所有要替换为图片的字段,Key中需包含image或者Value为图片的全路径
  6. * (目前只判断文件后缀名为:.bmp、.jpg、.gif)。
  7. * 要替换表格中的数据时,HashMap中的Key格式为“table$R@N”,其中:
  8. * R代表从表格的第R行开始替换,N代表word模板中的第N张表格;
  9. * Value为ArrayList对象,ArrayList中包含的对象统一为String[],一条String[]代表一行数据,
  10. * ArrayList中第一条记录为特殊记录,记录的是表格中要替换的列号,
  11. * 如:要替换第一列、第二列、第三列的数据,则第一条记录为String[3] {"1","2","3"}。
  12. */
  13.  
  14. import java.util.ArrayList;
  15. import java.util.HashMap;
  16. import java.util.Iterator;
  17.  
  18. import com.jacob.activeX.ActiveXComponent;
  19. import com.jacob.com.Dispatch;
  20. import com.jacob.com.Variant;
  21.  
  22. /**
  23. * 利用word模板生成word文件
  24. * @typename:Java2word
  25. * @author: FishRoad
  26. * @since: 2015年8月24日 下午2:47:41
  27. *
  28. */
  29. public class Java2word {
  30.  
  31. private boolean saveOnExit;
  32. /**
  33. * word文档
  34. */
  35. Dispatch doc = null;
  36.  
  37. /**
  38. * word运行程序对象s
  39. */
  40. private ActiveXComponent word;
  41. /**
  42. * 所有word文档
  43. */
  44. private Dispatch documents;
  45.  
  46. /**
  47. * 构造函数
  48. */
  49. public Java2word() {
  50. if(word==null){
  51. word = new ActiveXComponent("Word.Application");
  52. word.setProperty("Visible",new Variant(false));
  53. }
  54. if(documents==null)
  55. documents = word.getProperty("Documents").toDispatch();
  56. saveOnExit = false;
  57. }
  58.  
  59. /**
  60. * 设置参数:退出时是否保存
  61. * @param saveOnExit boolean true-退出时保存文件,false-退出时不保存文件
  62. */
  63. public void setSaveOnExit(boolean saveOnExit) {
  64. this.saveOnExit = saveOnExit;
  65. }
  66. /**
  67. * 得到参数:退出时是否保存
  68. * @return boolean true-退出时保存文件,false-退出时不保存文件
  69. */
  70. public boolean getSaveOnExit() {
  71. return saveOnExit;
  72. }
  73.  
  74. /**
  75. * 打开文件
  76. * @param inputDoc String 要打开的文件,全路径
  77. * @return Dispatch 打开的文件
  78. */
  79. public Dispatch open(String inputDoc) {
  80. return Dispatch.call(documents,"Open",inputDoc).toDispatch();
  81. }
  82.  
  83. /**
  84. * 选定内容
  85. * @return Dispatch 选定的范围或插入点
  86. */
  87. public Dispatch select() {
  88. return word.getProperty("Selection").toDispatch();
  89. }
  90.  
  91. /**
  92. * 把选定内容或插入点向上移动
  93. * @param selection Dispatch 要移动的内容
  94. * @param count int 移动的距离
  95. */
  96. public void moveUp(Dispatch selection,int count) {
  97. for(int i = 0;i < count;i ++)
  98. Dispatch.call(selection,"MoveUp");
  99. }
  100.  
  101. /**
  102. * 把选定内容或插入点向下移动
  103. * @param selection Dispatch 要移动的内容
  104. * @param count int 移动的距离
  105. */
  106. public void moveDown(Dispatch selection,int count) {
  107. for(int i = 0;i < count;i ++)
  108. Dispatch.call(selection,"MoveDown");
  109. }
  110.  
  111. /**
  112. * 把选定内容或插入点向左移动
  113. * @param selection Dispatch 要移动的内容
  114. * @param count int 移动的距离
  115. */
  116. public void moveLeft(Dispatch selection,int count) {
  117. for(int i = 0;i < count;i ++) {
  118. Dispatch.call(selection,"MoveLeft");
  119. }
  120. }
  121.  
  122. /**
  123. * 把选定内容或插入点向右移动
  124. * @param selection Dispatch 要移动的内容
  125. * @param count int 移动的距离
  126. */
  127. public void moveRight(Dispatch selection,int count) {
  128. for(int i = 0;i < count;i ++)
  129. Dispatch.call(selection,"MoveRight");
  130. }
  131.  
  132. /**
  133. * 把插入点移动到文件首位置
  134. * @param selection Dispatch 插入点
  135. */
  136. public void moveStart(Dispatch selection) {
  137. Dispatch.call(selection,"HomeKey",new Variant(6));
  138. }
  139.  
  140. /**
  141. * 从选定内容或插入点开始查找文本
  142. * @param selection Dispatch 选定内容
  143. * @param toFindText String 要查找的文本
  144. * @return boolean true-查找到并选中该文本,false-未查找到文本
  145. */
  146. public boolean find(Dispatch selection,String toFindText) {
  147. //从selection所在位置开始查询
  148. Dispatch find = word.call(selection,"Find").toDispatch();
  149. //设置要查找的内容
  150. Dispatch.put(find,"Text",toFindText);
  151. //向前查找
  152. Dispatch.put(find,"Forward","True");
  153. //设置格式
  154. Dispatch.put(find,"Format","True");
  155. //大小写匹配
  156. Dispatch.put(find,"MatchCase","True");
  157. //全字匹配
  158. Dispatch.put(find,"MatchWholeWord","True");
  159. //查找并选中
  160. return Dispatch.call(find,"Execute").getBoolean();
  161. }
  162.  
  163. /**
  164. * 把选定内容替换为设定文本
  165. * @param selection Dispatch 选定内容
  166. * @param newText String 替换为文本
  167. */
  168. public void replace(Dispatch selection,String newText) {
  169. //设置替换文本
  170. Dispatch.put(selection,"Text",newText);
  171. }
  172.  
  173. /**
  174. * 全局替换
  175. * @param selection Dispatch 选定内容或起始插入点
  176. * @param oldText String 要替换的文本
  177. * @param newText String 替换为文本
  178. */
  179. public void replaceAll(Dispatch selection,String oldText,Object replaceObj) {
  180. //移动到文件开头
  181. moveStart(selection);
  182.  
  183. if(oldText.startsWith("table") || replaceObj instanceof ArrayList)
  184. replaceTable(selection,oldText,(ArrayList) replaceObj);
  185. else {
  186. String newText = (String) replaceObj;
  187. if(newText==null)
  188. newText="";
  189. if(oldText.indexOf("image") != -1&!newText.trim().equals("") || newText.lastIndexOf(".bmp") != -1 || newText.lastIndexOf(".jpg") != -1 || newText.lastIndexOf(".gif") != -1){
  190. while(find(selection,oldText)) {
  191. replaceImage(selection,newText);
  192. Dispatch.call(selection,"MoveRight");
  193. }
  194. }else{
  195. while(find(selection,oldText)) {
  196. replace(selection,newText);
  197. Dispatch.call(selection,"MoveRight");
  198. }
  199. }
  200. }
  201. }
  202.  
  203. /**
  204. * 替换图片
  205. * @param selection Dispatch 图片的插入点
  206. * @param imagePath String 图片文件(全路径)
  207. */
  208. public void replaceImage(Dispatch selection,String imagePath) {
  209. Dispatch.call(Dispatch.get(selection,"InLineShapes").toDispatch(),"AddPicture",imagePath);
  210. }
  211.  
  212. /**
  213. * 替换表格
  214. * @param selection Dispatch 插入点
  215. * @param tableName String 表格名称,
  216. * 形如table$1@1、table$2@1...table$R@N,R代表从表格中的第N行开始填充,N代表word文件中的第N张表
  217. * @param fields HashMap 表格中要替换的字段与数据的对应表
  218. */
  219. public void replaceTable(Dispatch selection,String tableName,ArrayList dataList) {
  220. if(dataList.size() <= 1) {
  221. System.out.println("Empty table!");
  222. return;
  223. }
  224.  
  225. //要填充的列
  226. String[] cols = (String[]) dataList.get(0);
  227.  
  228. //表格序号
  229. String tbIndex = tableName.substring(tableName.lastIndexOf("@") + 1);
  230. //从第几行开始填充
  231. int fromRow = Integer.parseInt(tableName.substring(tableName.lastIndexOf("$") + 1,tableName.lastIndexOf("@")));
  232. //所有表格
  233. Dispatch tables = Dispatch.get(doc,"Tables").toDispatch();
  234. //要填充的表格
  235. Dispatch table = Dispatch.call(tables,"Item",new Variant(tbIndex)).toDispatch();
  236. //表格的所有行
  237. Dispatch rows = Dispatch.get(table,"Rows").toDispatch();
  238. //填充表格
  239. for(int i = 1;i < dataList.size();i ++) {
  240. //某一行数据
  241. String[] datas = (String[]) dataList.get(i);
  242.  
  243. //在表格中添加一行
  244. if(Dispatch.get(rows,"Count").getInt() < fromRow + i - 1)
  245. Dispatch.call(rows,"Add");
  246. //填充该行的相关列
  247. for(int j = 0;j < datas.length;j ++) {
  248. //得到单元格
  249. Dispatch cell = Dispatch.call(table,"Cell",Integer.toString(fromRow + i - 1),cols[j]).toDispatch();
  250. //选中单元格
  251. Dispatch.call(cell,"Select");
  252. //设置格式
  253. Dispatch font = Dispatch.get(selection,"Font").toDispatch();
  254. Dispatch.put(font,"Bold","0");
  255. Dispatch.put(font,"Italic","0");
  256. //输入数据
  257. Dispatch.put(selection,"Text",datas[j]);
  258. }
  259. }
  260. }
  261.  
  262. /**
  263. * 保存文件
  264. * @param outputPath String 输出文件(包含路径)
  265. */
  266. public void save(String outputPath) {
  267. Dispatch.call(Dispatch.call(word,"WordBasic").getDispatch(),"FileSaveAs",outputPath);
  268. }
  269.  
  270. /**
  271. * 关闭文件
  272. * @param document Dispatch 要关闭的文件
  273. */
  274. public void close(Dispatch doc) {
  275. Dispatch.call(doc,"Close",new Variant(saveOnExit));
  276. word.invoke("Quit",new Variant[]{});
  277. word = null;
  278. }
  279.  
  280. /**
  281. * 根据模板、数据生成word文件
  282. * @param inputPath String 模板文件(包含路径)
  283. * @param outPath String 输出文件(包含路径)
  284. * @param data HashMap 数据包(包含要填充的字段、对应的数据)
  285. */
  286. public void toWord(String inputPath,String outPath,HashMap data) {
  287. String oldText;
  288. Object newValue;
  289. try {
  290. if(doc==null)
  291. doc = open(inputPath);
  292.  
  293. Dispatch selection = select();
  294.  
  295. Iterator keys = data.keySet().iterator();
  296. while(keys.hasNext()) {
  297. oldText = (String) keys.next();
  298. newValue = data.get(oldText);
  299.  
  300. replaceAll(selection,oldText,newValue);
  301. }
  302.  
  303. save(outPath);
  304. } catch(Exception e) {
  305. System.out.println("操作word文件失败!");
  306. e.printStackTrace();
  307. } finally {
  308. if(doc != null)
  309. close(doc);
  310. }
  311. }
  312.  
  313. public synchronized static void word(String inputPath,String outPath,HashMap data){
  314. Java2word j2w = new Java2word();
  315. j2w.toWord(inputPath,outPath,data);
  316. }
  317.  
  318. @SuppressWarnings({ "rawtypes", "unchecked" })
  319. public static void main(String[] args) {
  320. //替换word中相关的字段
  321. HashMap data = new HashMap();
  322. data.put("$reportDept$","2007-8-1");
  323. data.put("$findDate$","2007-8-2");
  324. data.put("$finder$","kdl");
  325. data.put("$lineName$","5号线");
  326. data.put("$voltageRate$","11月13日");
  327. data.put("$towerNumberBound$","2004年11月10日");
  328. data.put("$image1$","C:\\Users\\Administrator\\Pictures\\1.jpg");
  329. data.put("$name$", "FishRoad");
  330. data.put("$age$", "24");
  331. //替换word中表格的数据
  332. /**
  333. * 要替换表格中的数据时,HashMap中的Key格式为“table$R@N”,其中:
  334. * R代表从表格的第R行开始替换,N代表word模板中的第N张表格;
  335. * Value为ArrayList对象,ArrayList中包含的对象统一为String[],
  336. * 一条String[]代表一行数据,ArrayList中第一条记录为特殊记录,记录的是表格中要替换的列号,
  337. * 如:要替换第一列、第二列、第三列的数据,则第一条记录为String[3] {"1","2","3"}
  338. */
  339. ArrayList table1 = new ArrayList(3);
  340. String[] fieldName1 = {"1","2","3"};
  341. table1.add(fieldName1);
  342. String[] field11 = {"1","751002","华夏证券"};
  343. table1.add(field11);
  344. String[] field21 = {"2","751004","国泰君安"};
  345. table1.add(field21);
  346. String[] field31 = {"3","751005","海通证券"};
  347. table1.add(field31);
  348. data.put("table$2@2",table1);
  349.  
  350. Java2word j2w = new Java2word();
  351. long time1 = System.currentTimeMillis();
  352. j2w.toWord("E:/template.doc","E:/result.doc",data);
  353. System.out.println("time cost : " + (System.currentTimeMillis() - time1));
  354. }
  355. }
  356.  
  357. 以上是相关的代码,接下来就要配置word模板,如下:
  358.  
  359. 导出的结果如下图:

利用模板导出文件(二)之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. JTopo使用心得

    因为工作关系,最近用到了拓扑图,找了一溜工具后,发现了这个--JTopo,纯国产而且免费 当然了如果你英文水平足够好的话.也可以看看这些英文的做拓扑图的工具,以下网站出自知乎回答:开源HTML5 绘图 ...

  2. Servlet模板,一个供新手参考的模板

    由于这学期老师的进度是刚开始教JavaSE部分,而我的进度比较快,所以买了3本javaee的书,我根据自己的基础,选择了合适的开发实践,另外两本书都和框架相关,我自认为我的web基础还不是很牢固,所以 ...

  3. hibernate框架模板(可复制修改)

    简易搭建jar包 User类 package com.littlepage.test; public class User { private int uid; private String unam ...

  4. JavaScript 局部刷新

    JavaScript局部刷新具体代码展示如下 1.  #tabList代表需要刷新的元素的对象 2.  第二个#tabList 如果后面有第三个元素,那么后面需要加>*符号,如果不加,容易造成C ...

  5. try catch对Spring事务的影响

    一.Spring 的默认事务机制,当出现unchecked异常时候回滚,checked异常的时候不会回滚. 异常中unchecked异常包括error和runtime异常.需要try catch或向上 ...

  6. winfrom 动态添加控件,以及删除

      private void btnadd_Click(object sender, EventArgs e)         {             int fileCount = 0;     ...

  7. 把 java web application deploy 到 root

    http://stackoverflow.com/questions/5328518/deploying-my-application-at-the-root-in-tomcat You have a ...

  8. 验证码之SimpleCaptcha (二)

    上回说到了简单的使用simpleCaptcha,这次我们这次我们将讲解扩张simpleCaptcha.       回到正题,我们需要一些自定义的验证码,比如验证码的字体大小,背景,颜色等等,默认的验 ...

  9. Ubuntu更改源和搜狗输入法安装卸载

    安装完Ubuntu 16.04后,要更换为国内的软件源: sudo gedit /etc/apt/sources.list   #用文本编辑器打开源列表 在文件开头添加下面的阿里云的软件源: deb ...

  10. Spring之Spel表达式

    正常业务场景一般不用这个技术,但需要知道有这么个东西支持Spring. 记忆力不好,抄了些套路代码便于以后用到. package com.paic.phssp.springtest.spel; imp ...