jacob读写word文档

 

介绍一下jacob:
jacob是在java与微软的com组件之间的桥梁,通过使用jacob自带的dll动态链接库通过jni的方式实现了在sun java平台上的程序对com调用!
下载地址:
http://sourceforge.net/project/showfiles.php?group_id=109543&package_id=118368

可用的版本很多,现在我用的是:jacob_1.11.1
功能:可以实现word与pdf和excel的操作,与转换!
JDK版本:jdk1.4
我实现的作用:使用插件:按照word规定的格式创建word 文件

配置说明::

解压文件:jacob_1.11.1.zip ,copy jacob.jar文件加入到classpath

copy jacob.dll 放在java jdk bin目录下

copy template.doc到web-inf下

注:template: 可以修改为自己的任意格式的doc
先看一下我的template.doc:
下面是我的类文件:Java2Word.java

下载: Java2Word.java
  1. package com.cenbow.web.produceword;
  2. /*************************************
  3. *
  4. *作用:利用jacob插件根据模板word生成word 文件!
  5. *
  6. *传入数据为HashMap对象,对象中的Key代表word模板中要替换的字段,Value代表用来替换的值。
  7. * word模板中所有要替换的字段(即HashMap中的Key)以特殊字符开头和结尾,如:$code$、$date$……,以免执行错误的替换。
  8. * 所有要替换为图片的字段,Key中需包含image或者Value为图片的全路径(目前只判断文件后缀名为:.bmp、.jpg、.gif)。
  9. * 要替换表格中的数据时,HashMap中的Key格式为“table$R@N”,其中:R代表从表格的第R行开始替换,N代表word模板中的第N张表格;
  10. * Value为ArrayList对象,ArrayList中包含的对象统一为String[],一条String[]代表一行数据,ArrayList中第一条记录为特殊记录,
  11. * 记录的是表格中要替换的列号,如:要替换第一列、第三列、第五列的数据,则第一条记录为String[3] {“1”,”3”,”5”}。
  12. *
  13. *
  14. *create on 2007.3.6
  15. *author fgl
  16. *
  17. *
  18. ************************************/
  19.  
  20. import java.util.Iterator;
  21. import java.util.List;
  22. import java.util.HashMap;
  23.  
  24. import com.jacob.activeX.ActiveXComponent;
  25. import com.jacob.com.ComThread;
  26. import com.jacob.com.Dispatch;
  27. import com.jacob.com.Variant;
  28.  
  29. public class Java2Word {
  30. private boolean saveOnExit;
  31. /**
  32. * word文档
  33. */
  34. private Dispatch doc = null;
  35. /**
  36. * word运行程序对象
  37. */
  38. private ActiveXComponent word;
  39. /**
  40. * 所有word文档
  41. */
  42. private Dispatch documents;
  43. /**
  44. * 构造函数
  45. */
  46. public Java2Word() {
  47. saveOnExit = false;
  48. word = new ActiveXComponent("Word.Application");
  49. word.setProperty("Visible",new Variant(false));
  50. documents = word.getProperty("Documents").toDispatch();
  51. }
  52. /**
  53. * 设置参数:退出时是否保存
  54. * @param saveOnExit true-退出时保存文件,false-退出时不保存文件
  55. */
  56. public void setSaveOnExit(boolean saveOnExit) {
  57. this.saveOnExit = saveOnExit;
  58. }
  59. /**
  60. * 得到参数:退出时是否保存
  61. * @return boolean true-退出时保存文件,false-退出时不保存文件
  62. */
  63. public boolean getSaveOnExit() {
  64. return saveOnExit;
  65. }
  66. /**
  67. * 打开文件
  68. * @param inputDoc 要打开的文件,全路径
  69. * @return Dispatch 打开的文件
  70. */
  71. public Dispatch open(String inputDoc) {
  72. return Dispatch.call(documents,"Open",inputDoc).toDispatch();
  73. }
  74. /**
  75. * 选定内容
  76. * @return Dispatch 选定的范围或插入点
  77. */
  78. public Dispatch select() {
  79. return word.getProperty("Selection").toDispatch();
  80. }
  81. /**
  82. * 把选定内容或插入点向上移动
  83. * @param selection 要移动的内容
  84. * @param count 移动的距离
  85. */
  86. public void moveUp(Dispatch selection,int count) {
  87. for(int i = 0;i < count;i++)
  88. Dispatch.call(selection,"MoveUp");
  89. }
  90. /**
  91. * 把选定内容或插入点向下移动
  92. * @param selection 要移动的内容
  93. * @param count 移动的距离
  94. */
  95. public void moveDown(Dispatch selection,int count) {
  96. for(int i = 0;i < count;i++)
  97. Dispatch.call(selection,"MoveDown");
  98. }
  99. /**
  100. * 把选定内容或插入点向左移动
  101. * @param selection 要移动的内容
  102. * @param count 移动的距离
  103. */
  104. public void moveLeft(Dispatch selection,int count) {
  105. for(int i = 0;i < count;i++)
  106. Dispatch.call(selection,"MoveLeft");
  107. }
  108. /**
  109. * 把选定内容或插入点向右移动
  110. * @param selection 要移动的内容
  111. * @param count 移动的距离
  112. */
  113. public void moveRight(Dispatch selection,int count) {
  114. for(int i = 0;i < count;i++)
  115. Dispatch.call(selection,"MoveRight");
  116. }
  117. /**
  118. * 把插入点移动到文件首位置
  119. * @param selection 插入点
  120. */
  121. public void moveStart(Dispatch selection) {
  122. Dispatch.call(selection,"HomeKey",new Variant(6));
  123. }
  124. /**
  125. * 从选定内容或插入点开始查找文本
  126. * @param selection 选定内容
  127. * @param toFindText 要查找的文本
  128. * @return boolean true-查找到并选中该文本,false-未查找到文本
  129. */
  130. public boolean find(Dispatch selection,String toFindText) {
  131. // 从selection所在位置开始查询
  132. Dispatch find = Dispatch.call(selection,"Find").toDispatch();
  133. // 设置要查找的内容
  134. Dispatch.put(find,"Text",toFindText);
  135. // 向前查找
  136. Dispatch.put(find,"Forward","True");
  137. // 设置格式
  138. Dispatch.put(find,"Format","True");
  139. // 大小写匹配
  140. Dispatch.put(find,"MatchCase","True");
  141. // 全字匹配
  142. Dispatch.put(find,"MatchWholeWord","True");
  143. // 查找并选中
  144. return Dispatch.call(find,"Execute").getBoolean();
  145. }
  146. /**
  147. * 把选定内容替换为设定文本
  148. * @param selection 选定内容
  149. * @param newText 替换为文本
  150. */
  151. public void replace(Dispatch selection,String newText) {
  152. // 设置替换文本
  153. Dispatch.put(selection,"Text",newText);
  154. }
  155. /**
  156. * 全局替换
  157. * @param selection 选定内容或起始插入点
  158. * @param oldText 要替换的文本
  159. * @param newText 替换为文本
  160. */
  161. public void replaceAll(Dispatch selection,String oldText,Object replaceObj) {
  162. // 移动到文件开头
  163. moveStart(selection);
  164. if(oldText.startsWith("table") || replaceObj instanceof List) {
  165. replaceTable(selection,oldText,(List) replaceObj);
  166. } else {
  167. String newText = (String) replaceObj;
  168. if(oldText.indexOf("image") != -1
  169. || newText.lastIndexOf(".bmp") != -1
  170. || newText.lastIndexOf(".jpg") != -1
  171. || newText.lastIndexOf(".gif") != -1)
  172. while (find(selection,oldText)) {
  173. replaceImage(selection,newText);
  174. Dispatch.call(selection,"MoveRight");
  175. }
  176. else
  177. while (find(selection,oldText)) {
  178. replace(selection,newText);
  179. Dispatch.call(selection,"MoveRight");
  180. }
  181. }
  182. }
  183. /**
  184. * 替换图片
  185. * @param selection 图片的插入点
  186. * @param imagePath 图片文件(全路径)
  187. */
  188. public void replaceImage(Dispatch selection,String imagePath) {
  189. Dispatch.call(Dispatch.get(selection,"InLineShapes").toDispatch(),"AddPicture",imagePath);
  190. }
  191. /**
  192. * 替换表格
  193. * @param selection 插入点
  194. * @param tableName 表格名称,形如table$1@1、table$2@1...table$R@N,R代表从表格中的第N行开始填充,
  195. *                  N代表word文件中的第N张表
  196. * @param fields 表格中要替换的字段与数据的对应表
  197. */
  198. public void replaceTable(Dispatch selection,String tableName,List dataList) {
  199. if(dataList.size() <= 1) {
  200. System.out.println("Empty table!");
  201. return;
  202. }
  203. // 要填充的列
  204. String[] cols = (String[]) dataList.get(0);
  205. // 表格序号
  206. String tbIndex = tableName.substring(tableName.lastIndexOf("@") + 1);
  207. // 从第几行开始填充
  208. int fromRow = Integer.parseInt(tableName.substring(tableName
  209. .lastIndexOf("$") + 1,tableName.lastIndexOf("@")));
  210. // 所有表格
  211. Dispatch tables = Dispatch.get(doc,"Tables").toDispatch();
  212. // 要填充的表格
  213. Dispatch table = Dispatch.call(tables,"Item",new Variant(tbIndex))
  214. .toDispatch();
  215. // 表格的所有行
  216. Dispatch rows = Dispatch.get(table,"Rows").toDispatch();
  217. // 填充表格
  218. for(int i = 1;i < dataList.size();i++) {
  219. // 某一行数据
  220. String[] datas = (String[]) dataList.get(i);
  221. // 在表格中添加一行
  222. if(Dispatch.get(rows,"Count").getInt() < fromRow + i - 1)
  223. Dispatch.call(rows,"Add");
  224. // 填充该行的相关列
  225. for(int j = 0;j < datas.length;j++) {
  226. // 得到单元格
  227. Dispatch cell = Dispatch.call(table,"Cell",
  228. Integer.toString(fromRow + i - 1),cols[j]).toDispatch();
  229. // 选中单元格
  230. Dispatch.call(cell,"Select");
  231. // 设置格式
  232. Dispatch font = Dispatch.get(selection,"Font").toDispatch();
  233. Dispatch.put(font,"Bold","0");
  234. Dispatch.put(font,"Italic","0");
  235. // 输入数据
  236. Dispatch.put(selection,"Text",datas[j]);
  237. }
  238. }
  239. }
  240. /**
  241. * 保存文件
  242. * @param outputPath 输出文件(包含路径)
  243. */
  244. public void save(String outputPath) {
  245. Dispatch.call(Dispatch.call(word,"WordBasic").getDispatch(),"FileSaveAs",outputPath);
  246. }
  247. /**
  248. * 关闭文件
  249. * @param document 要关闭的文件
  250. */
  251. public void close(Dispatch doc) {
  252. Dispatch.call(doc,"Close",new Variant(saveOnExit));
  253. }
  254.  
  255. /**
  256. * 退出程序
  257. */
  258. public void quit() {
  259. word.invoke("Quit",new Variant[0]);
  260. ComThread.Release();
  261. }
  262. /**
  263. * 根据模板、数据生成word文件
  264. * @param inputPath 模板文件(包含路径)
  265. * @param outPath 输出文件(包含路径)
  266. * @param data 数据包(包含要填充的字段、对应的数据)
  267. */
  268. public void toWord(String inputPath,String outPath,HashMap data) {
  269. String oldText;
  270. Object newValue;
  271. try {
  272. doc = open(inputPath);
  273. Dispatch selection = select();
  274. Iterator keys = data.keySet().iterator();
  275. while (keys.hasNext()) {
  276. oldText = (String) keys.next();
  277. newValue = data.get(oldText);
  278. replaceAll(selection,oldText,newValue);
  279. }
  280. save(outPath);
  281. } catch (Exception e) {
  282. // debug.println("toword[Java2Word]------------操作word文件失败!"+e.getMessage(),true);
  283.  
  284. } finally {
  285. if(doc != null)
  286. close(doc);
  287. }
  288. }
  289. }

下面是我在servlet调用的代码:

  1. HashMap data = new HashMap();
  2. data.put("$projects_title$",projects_title);
  3. data.put("$sort_name$",sort_name);
  4. data.put("$web_name$",web_name);
  5. data.put("$people_name$",people_name);
  6. data.put("$projects_manager$",projects_manager);
  7. data.put("$testaddresses$",testaddresses);
  8. data.put("$language_type$",language_type);
  9. data.put("$contact$",contact);
  10. data.put("$projects_progress$",projects_progress);
  11. data.put("$critique$",critique.toString());
  12.  
  13. try{
  14. Java2Word j2w = new Java2Word();
  15. long time1 = System.currentTimeMillis();
  16. j2w.toWord(debug.LOCALPATH+"WEB-INF/template.doc",debug.LOCALPATH+"WEB-INF/classes/com/cenbow/web/produceword/New.doc",data);
  17. j2w=null;
  18. //debug.println(operatorid,"processPost[ProduceWordServlet]-------------time cost : " + (System.currentTimeMillis() - time1),true);
  19. time1=0;
  20. }catch(Exception ex){
  21. // debug.println(operatorid,"processPost[ProduceWordServlet]-----------produceword failure:"+ex.getMessage(),true);
  22. }

注:这个操作只能在windows平台下实现!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值