Java操作Microsoft Word之jacob

转自:

现在我们一起来看看,用Java如何操作Microsoft Word。
 
jacob,官网是http://danadler.com/jacob 这是一个开源的工具。最新版本1.7
 
 
官方的解释是:The JACOB Project: A JAva-COM Bridge
 
这是官方对下载文件的说明:
  1. jacob.jar: a JAR file for the java classes which you must add to your CLASSPATH. The package names replace com.ms with com.jacob (for example com.ms.com.Variant maps to com.jacob.com.Variant.
  2. jacob.dll: a small Win32 DLL which you must add to your PATH.
  3. samples: provided in Java source and compiled form to demonstrate various features of the product. In particular, a set of wrapper classes for Microsoft® ADO are provided as samples.
 
开发环境:
JDK 1.6
MyEclipse Enterprise Workbench Version: 7.0 Milestone-1
Tomcat 5.5.27
现在MyEclipse中新建一个项目jacob,将jacob的jar包放到该项目的类库中。
我的jacob版本是1.14.3 。
下面这一步非常重要,就是拷贝jacob目录中jacob-1.14.3-x86.dll文件到系统环境变量目录中
一般情况就放在当前jdk中bin目录下。
这里有一个MSWordManager 类,是jacob官方发布的工具类,里面有大多数Java操作MS Office的工具。
  1 package com.test; 
  2 
  3 import java.sql.Connection; 
  4 import java.sql.DriverManager; 
  5 import java.sql.ResultSet; 
  6 import java.sql.Statement; 
  7 import java.util.ArrayList; 
  8 import java.util.List; 
  9 
 10 import com.jacob.activeX.ActiveXComponent; 
 11 import com.jacob.com.Dispatch; 
 12 import com.jacob.com.Variant; 
 13 
 14 public class MSWordManager { 
 15         // word文档 
 16         private Dispatch doc; 
 17 
 18         // word运行程序对象 
 19         private ActiveXComponent word; 
 20 
 21         // 所有word文档集合 
 22         private Dispatch documents; 
 23 
 24         // 选定的范围或插入点 
 25         private Dispatch selection; 
 26 
 27         private boolean saveOnExit = true; 
 28 
 29         /** *//** 
 30          *     
 31          * @param visible 为true表示word应用程序可见 
 32          */ 
 33         public MSWordManager(boolean visible) { 
 34                 if (word == null) { 
 35                         word = new ActiveXComponent("Word.Application"); 
 36                         word.setProperty("Visible", new Variant(visible)); 
 37                 } 
 38                 if (documents == null) 
 39                         documents = word.getProperty("Documents").toDispatch(); 
 40         } 
 41 
 42         /** *//** 
 43          * 设置退出时参数 
 44          *     
 45          * @param saveOnExit boolean true-退出时保存文件,false-退出时不保存文件 
 46          */ 
 47         public void setSaveOnExit(boolean saveOnExit) { 
 48                 this.saveOnExit = saveOnExit; 
 49         } 
 50 
 51         /** *//** 
 52          * 创建一个新的word文档 
 53          *     
 54          */ 
 55         public void createNewDocument() { 
 56                 doc = Dispatch.call(documents, "Add").toDispatch(); 
 57                 selection = Dispatch.get(word, "Selection").toDispatch(); 
 58         } 
 59 
 60         /** *//** 
 61          * 打开一个已存在的文档 
 62          *     
 63          * @param docPath 
 64          */ 
 65         public void openDocument(String docPath) { 
 66                 closeDocument(); 
 67                 doc = Dispatch.call(documents, "Open", docPath).toDispatch(); 
 68                 selection = Dispatch.get(word, "Selection").toDispatch(); 
 69         } 
 70 
 71         /** *//** 
 72          * 把选定的内容或插入点向上移动 
 73          *     
 74          * @param pos 移动的距离 
 75          */ 
 76         public void moveUp(int pos) { 
 77                 if (selection == null) 
 78                         selection = Dispatch.get(word, "Selection").toDispatch(); 
 79                 for (int i = 0; i < pos; i++) 
 80                         Dispatch.call(selection, "MoveUp"); 
 81 
 82         } 
 83 
 84         /** *//** 
 85          * 把选定的内容或者插入点向下移动 
 86          *     
 87          * @param pos 移动的距离 
 88          */ 
 89         public void moveDown(int pos) { 
 90                 if (selection == null) 
 91                         selection = Dispatch.get(word, "Selection").toDispatch(); 
 92                 for (int i = 0; i < pos; i++) 
 93                         Dispatch.call(selection, "MoveDown"); 
 94         } 
 95 
 96         /** *//** 
 97          * 把选定的内容或者插入点向左移动 
 98          *     
 99          * @param pos 移动的距离 
100          */ 
101         public void moveLeft(int pos) { 
102                 if (selection == null) 
103                         selection = Dispatch.get(word, "Selection").toDispatch(); 
104                 for (int i = 0; i < pos; i++) { 
105                         Dispatch.call(selection, "MoveLeft"); 
106                 } 
107         } 
108 
109         /** *//** 
110          * 把选定的内容或者插入点向右移动 
111          *     
112          * @param pos 移动的距离 
113          */ 
114         public void moveRight(int pos) { 
115                 if (selection == null) 
116                         selection = Dispatch.get(word, "Selection").toDispatch(); 
117                 for (int i = 0; i < pos; i++) 
118                         Dispatch.call(selection, "MoveRight"); 
119         } 
120 
121         /** *//** 
122          * 把插入点移动到文件首位置 
123          *     
124          */ 
125         public void moveStart() { 
126                 if (selection == null) 
127                         selection = Dispatch.get(word, "Selection").toDispatch(); 
128                 Dispatch.call(selection, "HomeKey", new Variant(6)); 
129         } 
130          
131         public void moveEnd() { 
132                 if (selection == null) 
133                         selection = Dispatch.get(word, "Selection").toDispatch(); 
134                 Dispatch.call(selection, "EndKey", new Variant(6)); 
135         } 
136 
137         /** *//** 
138          * 从选定内容或插入点开始查找文本 
139          *     
140          * @param toFindText 要查找的文本 
141          * @return boolean true-查找到并选中该文本,false-未查找到文本 
142          */ 
143         public boolean find(String toFindText) { 
144                 if (toFindText == null || toFindText.equals("")) 
145                         return false; 
146                 // 从selection所在位置开始查询 
147                 Dispatch find = word.call(selection, "Find").toDispatch(); 
148                 // 设置要查找的内容 
149                 Dispatch.put(find, "Text", toFindText); 
150                 // 向前查找 
151                 Dispatch.put(find, "Forward", "True"); 
152                 // 设置格式 
153                 Dispatch.put(find, "Format", "True"); 
154                 // 大小写匹配 
155                 Dispatch.put(find, "MatchCase", "True"); 
156                 // 全字匹配 
157                 Dispatch.put(find, "MatchWholeWord", "True"); 
158                 // 查找并选中 
159                 return Dispatch.call(find, "Execute").getBoolean(); 
160         } 
161 
162         /** *//** 
163          * 把选定选定内容设定为替换文本 
164          *     
165          * @param toFindText 查找字符串 
166          * @param newText 要替换的内容 
167          * @return 
168          */ 
169         public boolean replaceText(String toFindText, String newText) { 
170                 if (!find(toFindText)) 
171                         return false; 
172                 Dispatch.put(selection, "Text", newText); 
173                 return true; 
174         } 
175 
176         /** *//** 
177          * 全局替换文本 
178          *     
179          * @param toFindText 查找字符串 
180          * @param newText 要替换的内容 
181          */ 
182         public void replaceAllText(String toFindText, String newText) { 
183                 while (find(toFindText)) { 
184                         Dispatch.put(selection, "Text", newText); 
185                         Dispatch.call(selection, "MoveRight"); 
186                 } 
187         } 
188 
189         /** *//** 
190          * 在当前插入点插入字符串 
191          *     
192          * @param newText 要插入的新字符串 
193          */ 
194         public void insertText(String newText) { 
195                 Dispatch.put(selection, "Text", newText); 
196         } 
197 
198         /** *//** 
199          *     
200          * @param toFindText 要查找的字符串 
201          * @param imagePath 图片路径 
202          * @return 
203          */ 
204         public boolean replaceImage(String toFindText, String imagePath) { 
205                 if (!find(toFindText)) 
206                         return false; 
207                 Dispatch.call(Dispatch.get(selection, "InLineShapes").toDispatch(), 
208                                 "AddPicture", imagePath); 
209                 return true; 
210         } 
211 
212         /** *//** 
213          * 全局替换图片 
214          *     
215          * @param toFindText 查找字符串 
216          * @param imagePath 图片路径 
217          */ 
218         public void replaceAllImage(String toFindText, String imagePath) { 
219                 while (find(toFindText)) { 
220                         Dispatch.call(Dispatch.get(selection, "InLineShapes").toDispatch(), 
221                                         "AddPicture", imagePath); 
222                         Dispatch.call(selection, "MoveRight"); 
223                 } 
224         } 
225 
226         /** *//** 
227          * 在当前插入点插入图片 
228          *     
229          * @param imagePath 图片路径 
230          */ 
231         public void insertImage(String imagePath) { 
232                 Dispatch.call(Dispatch.get(selection, "InLineShapes").toDispatch(), 
233                                 "AddPicture", imagePath); 
234         } 
235 
236         /** *//** 
237          * 合并单元格 
238          *     
239          * @param tableIndex 
240          * @param fstCellRowIdx 
241          * @param fstCellColIdx 
242          * @param secCellRowIdx 
243          * @param secCellColIdx 
244          */ 
245         public void mergeCell(int tableIndex, int fstCellRowIdx, int fstCellColIdx, 
246                         int secCellRowIdx, int secCellColIdx) { 
247                 // 所有表格 
248                 Dispatch tables = Dispatch.get(doc, "Tables").toDispatch(); 
249                 // 要填充的表格 
250                 Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex)) 
251                                 .toDispatch(); 
252                 Dispatch fstCell = Dispatch.call(table, "Cell", 
253                                 new Variant(fstCellRowIdx), new Variant(fstCellColIdx)) 
254                                 .toDispatch(); 
255                 Dispatch secCell = Dispatch.call(table, "Cell", 
256                                 new Variant(secCellRowIdx), new Variant(secCellColIdx)) 
257                                 .toDispatch(); 
258                 Dispatch.call(fstCell, "Merge", secCell); 
259         } 
260 
261         /** *//** 
262          * 在指定的单元格里填写数据 
263          *     
264          * @param tableIndex 
265          * @param cellRowIdx 
266          * @param cellColIdx 
267          * @param txt 
268          */ 
269         public void putTxtToCell(int tableIndex, int cellRowIdx, int cellColIdx, 
270                         String txt) { 
271                 // 所有表格 
272                 Dispatch tables = Dispatch.get(doc, "Tables").toDispatch(); 
273                 // 要填充的表格 
274                 Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex)) 
275                                 .toDispatch(); 
276                 Dispatch cell = Dispatch.call(table, "Cell", new Variant(cellRowIdx), 
277                                 new Variant(cellColIdx)).toDispatch(); 
278                 Dispatch.call(cell, "Select"); 
279                 Dispatch.put(selection, "Text", txt); 
280         } 
281 
282         /** *//** 
283          * 在当前文档拷贝数据 
284          *     
285          * @param pos 
286          */ 
287         public void copy(String toCopyText) { 
288                 moveStart(); 
289                 if (this.find(toCopyText)) { 
290                         Dispatch textRange = Dispatch.get(selection, "Range").toDispatch(); 
291                         Dispatch.call(textRange, "Copy"); 
292                 } 
293         } 
294 
295         /** *//** 
296          * 在当前文档粘帖剪贴板数据 
297          *     
298          * @param pos 
299          */ 
300         public void paste(String pos) { 
301                 moveStart(); 
302                 if (this.find(pos)) { 
303                         Dispatch textRange = Dispatch.get(selection, "Range").toDispatch(); 
304                         Dispatch.call(textRange, "Paste"); 
305                 } 
306         } 
307 
308         /** *//** 
309          * 在当前文档指定的位置拷贝表格 
310          *     
311          * @param pos 当前文档指定的位置 
312          * @param tableIndex 被拷贝的表格在word文档中所处的位置 
313          */ 
314         public void copyTable(String pos,int tableIndex) { 
315                 Dispatch tables = Dispatch.get(doc, "Tables").toDispatch(); 
316                 Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex)) 
317                                 .toDispatch(); 
318                 Dispatch range = Dispatch.get(table, "Range").toDispatch(); 
319                 Dispatch.call(range, "Copy"); 
320                 if (this.find(pos)) { 
321                         Dispatch textRange = Dispatch.get(selection, "Range").toDispatch(); 
322                         Dispatch.call(textRange, "Paste"); 
323                 } 
324         } 
325 
326         /** *//** 
327          * 在当前文档末尾拷贝来自另一个文档中的段落 
328          *     
329          * @param anotherDocPath 另一个文档的磁盘路径 
330          * @param tableIndex 被拷贝的段落在另一格文档中的序号(从1开始) 
331          */ 
332         public void copyParagraphFromAnotherDoc(String anotherDocPath, 
333                         int paragraphIndex) { 
334                 Dispatch wordContent = Dispatch.get(doc, "Content").toDispatch(); // 取得当前文档的内容 
335                 Dispatch.call(wordContent, "InsertAfter", "$selection$");// 插入特殊符定位插入点 
336                 copyParagraphFromAnotherDoc(anotherDocPath, paragraphIndex, 
337                                 "$selection$"); 
338         } 
339 
340         /** *//** 
341          * 在当前文档指定的位置拷贝来自另一个文档中的段落 
342          *     
343          * @param anotherDocPath 另一个文档的磁盘路径 
344          * @param tableIndex 被拷贝的段落在另一格文档中的序号(从1开始) 
345          * @param pos 当前文档指定的位置 
346          */ 
347         public void copyParagraphFromAnotherDoc(String anotherDocPath, 
348                         int paragraphIndex, String pos) { 
349                 Dispatch doc2 = null; 
350                 try { 
351                         doc2 = Dispatch.call(documents, "Open", anotherDocPath) 
352                                         .toDispatch(); 
353                         Dispatch paragraphs = Dispatch.get(doc2, "Paragraphs").toDispatch(); 
354 
355                         Dispatch paragraph = Dispatch.call(paragraphs, "Item", 
356                                         new Variant(paragraphIndex)).toDispatch(); 
357                         Dispatch range = Dispatch.get(paragraph, "Range").toDispatch(); 
358                         Dispatch.call(range, "Copy"); 
359                         if (this.find(pos)) { 
360                                 Dispatch textRange = Dispatch.get(selection, "Range") 
361                                                 .toDispatch(); 
362                                 Dispatch.call(textRange, "Paste"); 
363                         } 
364                 } catch (Exception e) { 
365                         e.printStackTrace(); 
366                 } finally { 
367                         if (doc2 != null) { 
368                                 Dispatch.call(doc2, "Close", new Variant(saveOnExit)); 
369                                 doc2 = null; 
370                         } 
371                 } 
372         } 
373 
374         /** *//** 
375          * 在当前文档指定的位置拷贝来自另一个文档中的表格 
376          *     
377          * @param anotherDocPath 另一个文档的磁盘路径 
378          * @param tableIndex 被拷贝的表格在另一格文档中的序号(从1开始) 
379          * @param pos 当前文档指定的位置 
380          */ 
381         public void copyTableFromAnotherDoc(String anotherDocPath, int tableIndex, 
382                         String pos) { 
383                 Dispatch doc2 = null; 
384                 try { 
385                         doc2 = Dispatch.call(documents, "Open", anotherDocPath) 
386                                         .toDispatch(); 
387                         Dispatch tables = Dispatch.get(doc2, "Tables").toDispatch(); 
388                         Dispatch table = Dispatch.call(tables, "Item", 
389                                         new Variant(tableIndex)).toDispatch(); 
390                         Dispatch range = Dispatch.get(table, "Range").toDispatch(); 
391                         Dispatch.call(range, "Copy"); 
392                         if (this.find(pos)) { 
393                                 Dispatch textRange = Dispatch.get(selection, "Range") 
394                                                 .toDispatch(); 
395                                 Dispatch.call(textRange, "Paste"); 
396                         } 
397                 } catch (Exception e) { 
398                         e.printStackTrace(); 
399                 } finally { 
400                         if (doc2 != null) { 
401                                 Dispatch.call(doc2, "Close", new Variant(saveOnExit)); 
402                                 doc2 = null; 
403                         } 
404                 } 
405         } 
406 
407         /** *//** 
408          * 在当前文档指定的位置拷贝来自另一个文档中的图片 
409          *     
410          * @param anotherDocPath 另一个文档的磁盘路径 
411          * @param shapeIndex 被拷贝的图片在另一格文档中的位置 
412          * @param pos 当前文档指定的位置 
413          */ 
414         public void copyImageFromAnotherDoc(String anotherDocPath, int shapeIndex, 
415                         String pos) { 
416                 Dispatch doc2 = null; 
417                 try { 
418                         doc2 = Dispatch.call(documents, "Open", anotherDocPath) 
419                                         .toDispatch(); 
420                         Dispatch shapes = Dispatch.get(doc2, "InLineShapes").toDispatch(); 
421                         Dispatch shape = Dispatch.call(shapes, "Item", 
422                                         new Variant(shapeIndex)).toDispatch(); 
423                         Dispatch imageRange = Dispatch.get(shape, "Range").toDispatch(); 
424                         Dispatch.call(imageRange, "Copy"); 
425                         if (this.find(pos)) { 
426                                 Dispatch textRange = Dispatch.get(selection, "Range") 
427                                                 .toDispatch(); 
428                                 Dispatch.call(textRange, "Paste"); 
429                         } 
430                 } catch (Exception e) { 
431                         e.printStackTrace(); 
432                 } finally { 
433                         if (doc2 != null) { 
434                                 Dispatch.call(doc2, "Close", new Variant(saveOnExit)); 
435                                 doc2 = null; 
436                         } 
437                 } 
438         } 
439 
440         /** *//** 
441          * 创建表格 
442          *     
443          * @param pos    位置 
444          * @param cols 列数 
445          * @param rows 行数 
446          */ 
447         public void createTable(int numCols, int numRows){//(String pos, int numCols, int numRows) { 
448 //                if (!find(pos)) { 
449                         Dispatch tables = Dispatch.get(doc, "Tables").toDispatch(); 
450                         Dispatch range = Dispatch.get(selection, "Range").toDispatch(); 
451                         Dispatch newTable = Dispatch.call(tables, "Add", range, 
452                                         new Variant(numRows), new Variant(numCols)).toDispatch(); 
453                         Dispatch.call(selection, "MoveRight"); 
454                         moveEnd(); 
455 //                } 
456         } 
457 
458         /** *//** 
459          * 在指定行前面增加行 
460          *     
461          * @param tableIndex word文件中的第N张表(从1开始) 
462          * @param rowIndex 指定行的序号(从1开始) 
463          */ 
464         public void addTableRow(int tableIndex, int rowIndex) { 
465                 // 所有表格 
466                 Dispatch tables = Dispatch.get(doc, "Tables").toDispatch(); 
467                 // 要填充的表格 
468                 Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex)) 
469                                 .toDispatch(); 
470                 // 表格的所有行 
471                 Dispatch rows = Dispatch.get(table, "Rows").toDispatch(); 
472                 Dispatch row = Dispatch.call(rows, "Item", new Variant(rowIndex)) 
473                                 .toDispatch(); 
474                 Dispatch.call(rows, "Add", new Variant(row)); 
475         } 
476 
477         /** *//** 
478          * 在第1行前增加一行 
479          *     
480          * @param tableIndex word文档中的第N张表(从1开始) 
481          */ 
482         public void addFirstTableRow(int tableIndex) { 
483                 // 所有表格 
484                 Dispatch tables = Dispatch.get(doc, "Tables").toDispatch(); 
485                 // 要填充的表格 
486                 Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex)) 
487                                 .toDispatch(); 
488                 // 表格的所有行 
489                 Dispatch rows = Dispatch.get(table, "Rows").toDispatch(); 
490                 Dispatch row = Dispatch.get(rows, "First").toDispatch(); 
491                 Dispatch.call(rows, "Add", new Variant(row)); 
492         } 
493 
494         /** *//** 
495          * 在最后1行前增加一行 
496          *     
497          * @param tableIndex 
498          *                        word文档中的第N张表(从1开始) 
499          */ 
500         public void addLastTableRow(int tableIndex) { 
501                 // 所有表格 
502                 Dispatch tables = Dispatch.get(doc, "Tables").toDispatch(); 
503                 // 要填充的表格 
504                 Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex)) 
505                                 .toDispatch(); 
506                 // 表格的所有行 
507                 Dispatch rows = Dispatch.get(table, "Rows").toDispatch(); 
508                 Dispatch row = Dispatch.get(rows, "Last").toDispatch(); 
509                 Dispatch.call(rows, "Add", new Variant(row)); 
510         } 
511 
512         /** *//** 
513          * 增加一行 
514          *     
515          * @param tableIndex word文档中的第N张表(从1开始) 
516          */ 
517         public void addRow(int tableIndex) { 
518                 Dispatch tables = Dispatch.get(doc, "Tables").toDispatch(); 
519                 // 要填充的表格 
520                 Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex)) 
521                                 .toDispatch(); 
522                 // 表格的所有行 
523                 Dispatch rows = Dispatch.get(table, "Rows").toDispatch(); 
524                 Dispatch.call(rows, "Add"); 
525         } 
526 
527         /** *//** 
528          * 增加一列 
529          *     
530          * @param tableIndex word文档中的第N张表(从1开始) 
531          */ 
532         public void addCol(int tableIndex) { 
533                 // 所有表格 
534                 Dispatch tables = Dispatch.get(doc, "Tables").toDispatch(); 
535                 // 要填充的表格 
536                 Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex)) 
537                                 .toDispatch(); 
538                 // 表格的所有行 
539                 Dispatch cols = Dispatch.get(table, "Columns").toDispatch(); 
540                 Dispatch.call(cols, "Add").toDispatch(); 
541                 Dispatch.call(cols, "AutoFit"); 
542         } 
543 
544         /** *//** 
545          * 在指定列前面增加表格的列 
546          *     
547          * @param tableIndex word文档中的第N张表(从1开始) 
548          * @param colIndex    指定列的序号 (从1开始) 
549          */ 
550         public void addTableCol(int tableIndex, int colIndex) { 
551                 // 所有表格 
552                 Dispatch tables = Dispatch.get(doc, "Tables").toDispatch(); 
553                 // 要填充的表格 
554                 Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex)) 
555                                 .toDispatch(); 
556                 // 表格的所有行 
557                 Dispatch cols = Dispatch.get(table, "Columns").toDispatch(); 
558                 System.out.println(Dispatch.get(cols, "Count")); 
559                 Dispatch col = Dispatch.call(cols, "Item", new Variant(colIndex)) 
560                                 .toDispatch(); 
561                 // Dispatch col = Dispatch.get(cols, "First").toDispatch(); 
562                 Dispatch.call(cols, "Add", col).toDispatch(); 
563                 Dispatch.call(cols, "AutoFit"); 
564         } 
565 
566         /** *//** 
567          * 在第1列前增加一列 
568          *     
569          * @param tableIndex word文档中的第N张表(从1开始) 
570          */ 
571         public void addFirstTableCol(int tableIndex) { 
572                 Dispatch tables = Dispatch.get(doc, "Tables").toDispatch(); 
573                 // 要填充的表格 
574                 Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex)) 
575                                 .toDispatch(); 
576                 // 表格的所有行 
577                 Dispatch cols = Dispatch.get(table, "Columns").toDispatch(); 
578                 Dispatch col = Dispatch.get(cols, "First").toDispatch(); 
579                 Dispatch.call(cols, "Add", col).toDispatch(); 
580                 Dispatch.call(cols, "AutoFit"); 
581         } 
582 
583         /** *//** 
584          * 在最后一列前增加一列 
585          *     
586          * @param tableIndex word文档中的第N张表(从1开始) 
587          */ 
588         public void addLastTableCol(int tableIndex) { 
589                 Dispatch tables = Dispatch.get(doc, "Tables").toDispatch(); 
590                 // 要填充的表格 
591                 Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex)) 
592                                 .toDispatch(); 
593                 // 表格的所有行 
594                 Dispatch cols = Dispatch.get(table, "Columns").toDispatch(); 
595                 Dispatch col = Dispatch.get(cols, "Last").toDispatch(); 
596                 Dispatch.call(cols, "Add", col).toDispatch(); 
597                 Dispatch.call(cols, "AutoFit"); 
598         } 
599 
600         /** *//** 
601          * 自动调整表格 
602          *     
603          */ 
604         public void autoFitTable() { 
605                 Dispatch tables = Dispatch.get(doc, "Tables").toDispatch(); 
606                 int count = Dispatch.get(tables, "Count").toInt(); 
607                 for (int i = 0; i < count; i++) { 
608                         Dispatch table = Dispatch.call(tables, "Item", new Variant(i + 1)) 
609                                         .toDispatch(); 
610                         Dispatch cols = Dispatch.get(table, "Columns").toDispatch(); 
611                         Dispatch.call(cols, "AutoFit"); 
612                 } 
613         } 
614 
615         /** *//** 
616          * 调用word里的宏以调整表格的宽度,其中宏保存在document下 
617          *     
618          */ 
619         public void callWordMacro() { 
620                 Dispatch tables = Dispatch.get(doc, "Tables").toDispatch(); 
621                 int count = Dispatch.get(tables, "Count").toInt(); 
622                 Variant vMacroName = new Variant("Normal.NewMacros.tableFit"); 
623                 Variant vParam = new Variant("param1"); 
624                 Variant para[] = new Variant[] { vMacroName }; 
625                 for (int i = 0; i < para.length; i++) { 
626                         Dispatch table = Dispatch.call(tables, "Item", new Variant(i + 1)) 
627                                         .toDispatch(); 
628                         Dispatch.call(table, "Select"); 
629                         Dispatch.call(word, "Run", "tableFitContent"); 
630                 } 
631         } 
632 
633         /** *//** 
634          * 设置当前选定内容的字体 
635          *     
636          * @param boldSize 
637          * @param italicSize 
638          * @param underLineSize 下划线 
639          * @param colorSize 字体颜色 
640          * @param size 字体大小 
641          * @param name 字体名称 
642          */ 
643         public void setFont(boolean bold, boolean italic, boolean underLine, 
644                         String colorSize, String size, String name) { 
645                 Dispatch font = Dispatch.get(selection, "Font").toDispatch(); 
646                 Dispatch.put(font, "Name", new Variant(name)); 
647                 Dispatch.put(font, "Bold", new Variant(bold)); 
648                 Dispatch.put(font, "Italic", new Variant(italic)); 
649                 Dispatch.put(font, "Underline", new Variant(underLine)); 
650                 Dispatch.put(font, "Color", colorSize); 
651                 Dispatch.put(font, "Size", size); 
652         } 
653 
654         /** *//** 
655          * 文件保存或另存为 
656          *     
657          * @param savePath 保存或另存为路径 
658          */ 
659         public void save(String savePath) { 
660                 Dispatch.call( 
661                                 (Dispatch) Dispatch.call(word, "WordBasic").getDispatch(), 
662                                 "FileSaveAs", savePath); 
663         } 
664 
665         /** *//** 
666          * 关闭当前word文档 
667          *     
668          */ 
669         public void closeDocument() { 
670                 if (doc != null) { 
671                         Dispatch.call(doc, "Save"); 
672                         Dispatch.call(doc, "Close", new Variant(saveOnExit)); 
673                         doc = null; 
674                 } 
675         } 
676 
677         /** *//** 
678          * 关闭全部应用 
679          *     
680          */ 
681         public void close() { 
682                 closeDocument(); 
683                 if (word != null) { 
684                         Dispatch.call(word, "Quit"); 
685                         word = null; 
686                 } 
687                 selection = null; 
688                 documents = null; 
689         } 
690 
691         /** *//** 
692          * 打印当前word文档 
693          *     
694          */ 
695         public void printFile() { 
696                 if (doc != null) { 
697                         Dispatch.call(doc, "PrintOut"); 
698                 } 
699         } 
700 
701         public static void main(String args[])throws Exception { 
702      
703      
704 
705                 MSWordManager msWordManager = new MSWordManager(true); 
706                 msWordManager.createNewDocument(); 
707 
708                  
709                  
710                 msWordManager.insertText("aaaaaaaaaaaaaaaaaaaaa"); 
711                 msWordManager.moveEnd(); 
712 
713              
714                  
715              
716                 msWordManager.close(); 
717 
718         } 
719          
720          
721 }
新建一个类T,来测试一下jacob是否能用,代码如下
 1 package com.test;     
 2 
 3 public class T {     
 4 
 5         public static void main(String[] args) {     
 6                 // TODO Auto-generated method stub    
 7                      MSWordManager ms=new MSWordManager(true);     
 8 //生成一个MSwordManager对象,并且设置显示Word程序    
 9                      ms.createNewDocument();     
10 //创建一个新的.doc文件    
11                      ms.insertText("Test jacob");     
12 //插入文本    
13                      ms.save("c:\1.doc");     
14 //保存.doc文件    
15                      ms.close();     
16                      ms.closeDocument();     
17         }     
18 
19 }
 
运行后C盘生成了1.doc文件,
这样也是没有实际意义,所以我们要加入数据库。
数据库依然是DB2 9.5 ,用户名db2admin 密码abc 表名admin
我在这个项目中添加了Hibernate框架,Java程序代码如下
 1 package com.dao;     
 2 
 3 import java.util.List;     
 4 
 5 public class Test {     
 6         public static void main(String[] args) {     
 7                 AdminDAO dao = new AdminDAO();     
 8                 List list = dao.findAll();     
 9                 MSWordManager ms=new MSWordManager(false);     
10                 ms.createNewDocument();     
11                 for (int i=1;i<=list.size();i++){     
12                         Admin admin = (Admin)list.get(1);     
13                         ms.insertText(admin.getName());     
14                         ms.insertText("本文章由jacob自动生成");     
15                         ms.moveEnd();     
16                 }     
17                  ms.save("c:\1.doc");     
18                  ms.closeDocument();     
19                  ms.close();                 
20         }     
21 } 
运行程序后,进入c盘,打开生成的1.doc文件。
这就是Java利用开源工具jacob操作Microsoft Word,至于其他MS Office软件,我会在以后的文章中继续发布。
下次我们一起看看用POI操作Microsoft Word。
原文地址:https://www.cnblogs.com/x_wukong/p/4270867.html