java jacob 操作word 文档,进行写操作
基于JACOB的WORD文档操作技术

龙源期刊网
基于JACOB的WORD文档操作技术
作者:车晓波闫旭琴刘晓建
来源:《科技创新导报》2013年第04期
在项目实施中,常常需要将系统运行结果、工程设计方案或者自定义内容作为WORD文档输出,以方便用户查看。
单纯依靠人工编写项目报告、填写设计内容不仅工作量大,而且容易出错。
因此,规范准确的WORD文档自动生成功能具有重要的应用价值。
由于WORD文档使用了复合文档格式,这种文档不能通过类似调用普通的文件操作函数来进行操作。
不少技术人员在WORD文档的控制方法上进行了探讨,文献中介绍了在VC++平台下使用COM技术调用OLE自动化对象,一般是通过加载OFFICE自带的对象库创建内部组件对象,通过对这些对象的操作实现WORD的自动化。
文献介绍了如何通过VC++调用VBA将报表内容输出到WORD应用程序中。
文献介绍了在JAVA中运用JACOB和基于COM组件的数据源之间的数据结构转换。
诸多文献讲述了在VC++平台下实现WORD自动化的操作,而在JAVA平台下进行WORD自动化的介绍并不多见,JAVA语言自面世以来,因其平台的独立性、安全性、
面向对象及多线程等特征,得到了广泛的应用。
该文将介绍一种通过JACOB创建COM对象来操作WORD文档的方法,实现了文档的自动生成,可以在制作复杂报表方面取得较好效果,充分体现了JAVA作为开发工具良好的可扩展性。
jacob常用的方法

通过Java调用OCX控件有几种方法,JNI、JACOB、Jawin等1.JNI最直接的方式,也是最麻烦的方式,需要自己完成所有的工作,不推荐。
2.Jawin尝试了一下,效果不错,但相对来说,其编程风格更贴近Windows,离Java有点远3.Jacob使用Jacob非常方便,Java编程风格,需要了解的知识比较少。
下载地址/projects/jacob-project/Jacob的使用方法1.初始化ComThread.InitMTA(true);ActiveXComponent com = new ActiveXComponent("组件的ProgID") ;Dispatch disp = com.getObject();2.调用控件里面的方面2.1调用无参的方法,并返回一个short值Dispatch.call(disp, "Init").getShort();2.2调用有一个参数的方法,并返回一个boolean值Dispatch.call(disp,"Method",new Variant(args)).getBoolean();调用多个参数依次类推,注意在传递参数前,将Java中的参数转换成Variant。
问题解决在使用Jacob调用OCX控件时,总是出一个异常Exception in thread "main" FailException: A COM exception has been encountered:At Invoke of: InitDescription: 灾难性故障通过Jawin调用,会出现8000FFFF错误。
这个错误是由ActiveX结构设计造成的。
在Ole4.0版本之前,外部程序是可以直接调用OCX中方法的。
Ole4.0之后,每次调用控件中的方法,系统会自动检查是否允许调用,即运行COleControl.IsInvokeAllowed (DISPID) 该方法检查控件是否正确的初始化或者是否通过持久存储接口正确加载,如果两个条件有一个满足,即返回TRUE,否则返回FALSE。
Jacob操作office文档

Jacob操作office文档dispatchdocs=app.getproperty(\doc=dispatch.invoke(docs,\newobject[]{srcfilepat h,新变体(错误),newvariant(true),//是否只读newvariant(false),newvariant(\newint[1]).todispatch();//调度。
Put(DOC,\//兼容性检查。
具体值false不正确dispatch.put(doc,\派遣调用(doc,\pdffilepath,wdformatpdf);//Word保存为PDF宏,值为17if(doc!=null){派遣打电话(医生,\}if(app!=null){应用程序。
调用(\}jacob操作pptdispatchppts=app。
getproperty(\//因power.exe的发布规则为同步,所以设置为同步发布ppt=dispatch.call(ppts,\true,//untitled指定文件是否有标题false//withwindow指定文件是否可见).todispatch();派遣呼叫(ppt、\pdffilepath、ppsaveaspdf);//Ppsaveaspdf是32的特定值if(ppt!=null){派遣电话(ppt,\}if(app!=null){应用程序。
调用(\}jacob操作excelimportjava。
伊奥。
objectinputstream。
格特菲尔德;importjava。
util。
arraylist;importjava。
util。
日期importjava。
util。
列表publicclassready{privatedispatchsheets=null;//获取图纸集合对象privatedispatchcurrentsheet=null//当前图纸/***打开excel文件*@Paramfilepath文件路径名*@paramvisible显示打开*@paramreadonly是否只读方式打开*/privatevoidopenexcel(stringfilepath,booleanvisible){try{xl.setproperty(\设置是否显示打开excelif(workbooks==null)工作簿=xl。
Java利用jacob实现文档格式转换

Java利⽤jacob实现⽂档格式转换实现⽂档格式之间的转换,我使⽤的是jacob-1.7版本,需要jacob.jar来调⽤activex控件,本机需安装WPS/office,还需要jacob.jar以及jacob.dll其中:jacob.dll 需要放置在系统system32下,如果系统是c盘:C://windows/system32/下⾯jacob.dll放在类似这样的⽬录下,D:\\jre1.8.0_31\binpublic class Word2Pdf {/*将office word⽂档转换为PDF*/public void word2PDF(String inputFile,String pdfFile){//打开word应⽤程序ActiveXComponent app = new ActiveXComponent("Word.Application");try {//设置word不可见,否则会弹出word界⾯app.setProperty("Visible", new Variant(false));//获得word中所有打开的⽂档,返回Documents对象Dispatch docs = app.getProperty("Documents").toDispatch();//调⽤Documents对象中Open⽅法打开⽂档,并返回打开的⽂档对象DocumentDispatch doc = Dispatch.call(docs, "Open", inputFile).toDispatch();//调⽤Document对象的SaveAs⽅法,将⽂档保存为pdf格式Dispatch.call(doc,"SaveAs",new Variant(pdfFile),17 //word保存为pdf格式);//关闭⽂档Dispatch.call(doc, "Close",true);//关闭word应⽤程序app.invoke("Quit");} catch (Exception e) {System.out.println(e.getMessage());app.invoke("Quit");}}/*将office excel⽂档转换为PDF*/public void excel2PDF(String inputFile,String pdfFile){//打开excel应⽤程序ActiveXComponent app = new ActiveXComponent("Excel.Application");try {//设置excel不可见,否则会弹出word界⾯app.setProperty("Visible", false);//获得excel中所有打开的⽂档,返回Workbooks对象Dispatch excels = app.getProperty("Workbooks").toDispatch();//调⽤Workbooks对象中Open⽅法打开⽂档,并返回打开的⽂档对象excelDispatch excel = Dispatch.call(excels, "Open", inputFile, false, true).toDispatch();//调⽤excel对象的SaveAs⽅法,将⽂档保存为pdf格式Dispatch.call(excel,"ExportAsFixedFormat",0, //excel保存为pdf格式pdfFile);//关闭⽂档Dispatch.call(excel, "Close",true);//关闭excel应⽤程序app.invoke("Quit");} catch (Exception e) {System.out.println(e.getMessage());app.invoke("Quit");}}/*将office ppt⽂档转换为PDF*/public void ppt2PDF(String inputFile,String pdfFile){//打开ppt应⽤程序ActiveXComponent app = new ActiveXComponent("PowerPoint.Application");try {//设置ppt不可见,否则会弹出ppt界⾯/*app.setProperty("Visible", new Variant(false));*///获得ppt中所有打开的⽂档,返回ppts对象Dispatch ppts = app.getProperty("Presentations").toDispatch();//调⽤ppts对象中Open⽅法打开⽂档,并返回打开的⽂档对象pptDispatch ppt = Dispatch.call(ppts, "Open", inputFile,true,// ReadOnlytrue,// Untitled指定⽂件是否有标题false// WithWindow指定⽂件是否可见).toDispatch();//调⽤ppt对象的SaveAs⽅法,将⽂档保存为pdf格式Dispatch.call(ppt,"SaveAs",/*"ExportAsFixedFormat",*/pdfFile,32 //ppt保存为pdf格式);//关闭⽂档Dispatch.call(ppt, "Close",true);//关闭ppt应⽤程序app.invoke("Quit");} catch (Exception e) {System.out.println(e.getMessage());app.invoke("Quit");}}public static void main(String[] args) throws Exception {Word2Pdf word2Pdf = new Word2Pdf();/*word2Pdf.word2PDF("D:/test/#6测试⽂档.docx", "D:/test/#6测试⽂档");*//*word2Pdf.excel2PDF("D:/test/燃机控制油系统巡检卡.xlsx", "D:/test/燃机控制油系统巡检卡");*/ /*word2Pdf.ppt2PDF("D:/test/设计.pptx", "D:/test/设计.pdf");*/}}。
Jacob操作Word详细教程

Jacob操作Word详细教程博客分类:java技术JavaTomcatQQ应用服务器F#首先,大家先要了解一下jacob ,官方的解释是Java COM Bridge,即java和 com组件间的桥梁,这里说说为什么我们用jacob操纵word。
而不直接使用java去做?这要原因:在Java开源世界没有很好工具来操作Word文档,POI对word操作还是很不完善,所以我们无法使用它很方便操作word文档来满足我们需求。
相比之下使用jacob操作word文档非常方便。
也比较容易。
jacob 下载地址:/jacob/这个网址还可以下载到源码和例子程序jacob 使用方法:将jacob1.7里面jacob.jar添加到我们应用程序环境中,并将 jacob.dl(l就是我前面说的com组件)把放到c:/windows/system32下。
如果是web环境中,需要将jacod.jar放到Tomcat的lib目录下.(如果用Tomcat服务器)值得注意的是,不同的版本的系统使用不同的dll文件所以如果你编译成功,但运行失败一般是dll文件问题遇到这种情况,可以到/jacob-project/jacob_1.9.zip?modtime= 1109437002&big_mirror=0下载其他的版本的 dll 文件。
下面这段程序是我在别人代码基础上进行一些改进(增加了一些新方法,渴望各位同行批评指正)Java代码1.package com.bperp.word.util;2.3.import java.io.BufferedInputStream;4.import java.io.BufferedOutputStream;5.import java.io.File;6.import java.io.FileInputStream;7.import java.io.FileOutputStream;8.import java.io.InputStream;9.import java.io.OutputStream;10.import java.text.SimpleDateFormat;11.import java.util.ArrayList;12.import java.util.Date;13.import java.util.HashMap;14.import java.util.Iterator;15.import java.util.List;16.import java.util.Map;17.import java.util.Set;18.19.public class WordWriter {20.21. private WordOperator word;22.23. public WordWriter(String filePath){24. word=new WordOperator();25. word.openDocument(filePath);26. }27.28. public WordWriter(InputStream input,String filePath,StringfileName) throws Exception{29. String path=saveAsDocFile(input,filePath,fileName);30. word=new WordOperator();31. word.openDocument(path);32. }33. /**34. * 将word文档输入流保存为本地得到word文件35. * @param input36. * @param filePath37. * @param fileName38. * @throws Exception39. */40. @SuppressWarnings("unused")41. private String saveAsDocFile(InputStream input,String filePath,String fileName)throws Exception{42. if(!StringUtils.isValidateString(filePath)||!StringUtils.isValidateString(fileName)){43. throw new Exception("The filePath or fileName is error");44. }45. if(input==null){46. throw new Exception("InputStream is null");47. }48. File file=new File(filePath);49.50. if(!file.exists()){51. throw new Exception(" The FilePath is null");52. }53. filePath = validateFilePath(filePath);54. fileName = getRandomFileName(fileName);55. InputStream in=null;56. OutputStream out=null;57. try{58. in=new BufferedInputStream(input);59. out=new BufferedOutputStream(new FileOutputStream(filePath+fileName));60. byte[] b=new byte[1024];61. for(int p=0; (p=in.read(b))!=-1;){62. out.write(b);63. out.flush();64. }65. }finally{66. if(out!=null){67. out.close();68. }69. if(in!=null){70. in.close();71. }72. }73. return filePath+fileName;74. }75. /**76. * 验证Word文件路径77. * @param filePath78. * @return79. */80. private String validateFilePath(String filePath) {81. if((stIndexOf("\\\\")==-1)&&(stIndexOf("/")==-1)){82. filePath=filePath+"/";83. }84. return filePath;85. }86. /**87. * 生成一个新的文件名(保证文件名不相同)88. * @param fileName89. * @return90. */91. private String getRandomFileName(String fileName) {92. fileName= fileName + "_"+ new SimpleDateFormat("yyyyMMddHHmmssZ").format(new Date())+".doc";93. return fileName;94. }95. /**96. * replaceText97. * @param map98. */99. public void replaceAllText(Map<String,String> map){ 100. if(map==null){101. return;102. }103. Set<String> keys=map.keySet();104. Iterator<String> it=keys.iterator();105. while(it.hasNext()){106. String key=it.next();107. word.replaceAllText(key, map.get(key)); 108. }109. }110. /**111. * add details112. * @param values113. */114. public void insertContextInRow(List<Map<String,String> > values,int tableIndex){115. if(tableIndex<=1){116. tableIndex=1;117. }118. if(values==null||values.size()<=0){119. return;120. }121. int[] p=null;122. Map<String,String> m=values.get(0);123. Set<String> keys=m.keySet();124. Iterator<String> it=keys.iterator();125. while(it.hasNext()){126. String str=it.next();127.128. int[] a=word.getTableCellPostion(str, tableInd ex);129. if(a!=null&&a[0]!=0){130. p=a;131. }132.133. }134. if(p!=null&&p[0]!=0){135. for(int i=1;i<values.size();i++){136. word.addTableRow(tableIndex,p[0]);//在表格插入行数137. }138. }139.140. Iterator<String> it2=keys.iterator();141. while(it2.hasNext()){142. int row=p[0];143. int col=0;144. String str=it2.next();145.146. int[]a=word.getTableCellPostion(str, tableInde x);147. if(a!=null){148. col=a[1];149. }150. for(Map<String,String> map:values){151. word.putTxtToCell(tableIndex, row, col, ma p.get(str));152. row++;153. }154. }155.156. }157.158. /**159. * close document160. */161. public void close(){162. word.closeDocument();163. word.close();164. }165. /**166. * 依据Word文件完整路径删除文件167. * @param path168. * @throws Exception169. */170. public void deleteWordFile(String path) throws Excepti on{171. File f=new File(path);172. if(!f.exists()){173. throw new Exception("The file is not exists");174. }175. f.delete();176. }177.178. /**179. *180. * @param args181. * @throws Exception182. */183. public static void main(String args[]) throws Exceptio n{184. InputStream in=new FileInputStream("d:\\aaa.doc");185. String path="d:\\qq";186. String fileName="aaa";187. WordWriter writer=new WordWriter(in,path,fileName) ;188. Map<String,String> map1=new HashMap<String,String> ();189. map1.put("p21", "上海商哲");190. map1.put("p12", "1550");191. writer.replaceAllText(map1);192. List<Map<String,String>> values =new ArrayList<Map <String,String>>();193. for(int i=0;i<10;i++){194. Map<String,String> map=new HashMap<String,String>( );195. map.put("$1", "111111111111");196. map.put("$2", "222222222222");197. map.put("$3", "333333333333");198. map.put("$4", "444444444444");199. map.put("$5", "555555555555");200. map.put("$6", "666666666666");201. values.add(map);202. }203. writer.insertContextInRow(values, 1);204. writer.close();205. }206.}。
【jacobword】使用jacob,合并多个word为一个word文件

【jacobword】使⽤jacob,合并多个word为⼀个word⽂件将⼏个word⽂件合并到⼀个word⽂件,使⽤注意点:1.后⾯附项⽬运⽤的jar包jacob-1.9,2.并且jacob运⽤中,需要将附件内的jacob.dll放到windows/system32下语法介绍:将⼀个关于JACOB的代码分成下⾯⼏个步骤:1) ActiveXComponent ax = new ActiveXComponent("a1");//构建ActiveX组件实例其中的a1的值和你需要调⽤的ActiveX控件有关MS控件名a1的值InternetExplorer InternetExplorer.ApplicationExcel Excel.ApplicationWord Word.ApplicationPowerpoint Powerpoint.Applicationvb/java Script ScriptControlwindows media Player WMPlayer.OCXOutlook Outlook.ApplicationVisio Visio.ApplicationDAO DAO.PrivateDBEngine.35MultiFace MultiFace.Face2) Dispatch ds = ax.getObject(). toDispatch();//获取Dispatch对象,我们可以把每个Dispatch对象看成是对Activex控件的⼀个操作,这⼀步是获得该ActiveX控件的控制权。
(注:浅析JACOB 中提到过Variant类,这⾥的ax.getObject()便是获得该对象,我们将其转化为任何对象(类型))3) Dispatch ds1 = Dispatch.get(ds, "a2").toDispatch(); //获取该ActiveX对象数据结构中的a2属性4) Dispatch d2 = Dispatch.invoke(ds1, "a3", a4, a5, a6).toDispatch(); //功能调⽤,对ActiveX对象ds1的a3属性执⾏a4(Dispatch.Put\Dispatch.Get等)操作,执⾏后a3的值为a5,a6为错误参数码常定义为new int[1],(注:call、get和put⽅法都是通过该⽅法实现的)5) Dispatch ds2 = Dispatch.put(ds, "a7","a8").toDispatch();//将ActiveX对象ds的属性a7的值设置为a8,该⽅法返回类型同get⼀样6) Dispatch ds3 = Dispatch.call(ds1, "a9", a10);//该⽅法和get⽅法⾮常类似,他是把a9属性赋值给a10具体的使⽤例⼦【将多个word合并成⼀个word⽂档】:1》⾸先将架包jacob-1.9放在lib,build path进项⽬2》将jacob.dll放在C:\Windows\System32下1package aaatest;23import java.util.ArrayList;4import java.util.List;56import com.jacob.activeX.ActiveXComponent;7import .Dispatch;8import .Variant;910public class WordTest {1112public static void main(String[] args) {13 List list = new ArrayList();14 String file1= "D:\\2.doc";15 String file2= "D:\\1.doc";16//String file3= "D:\\2.docx";17 list.add(file1);18 list.add(file2);19//list.add(file3);20 uniteDoc(list,"d:\\file.doc");21 }22public static void uniteDoc(List fileList, String savepaths) {23if (fileList.size() == 0 || fileList == null) {24return;25 }26//打开word27 ActiveXComponent app = new ActiveXComponent("Word.Application");//启动word28try {2930// 设置word不可见 ---也就是设置ActiveXComponent对象的⼀个属性31 app.setProperty("Visible", new Variant(false));32//获得documents对象----Variant。
jacob操作word

最近由于工作的原因需要对Word进行操作,并且在文档上面加上水印,这个问题我在网上搜索了很久都没有一个完整的解决办法,没得办法之好自己研究了,半天的努力没有白费,终于解决了,有兴趣的朋友可以参考下:环境:jdk1.4jacob 1.9office2003至于jacob的设置我就不用多说了,网上很多这样的文章,下面就把我的代码贴出来,供大家参考。
package src;import com.jacob.activeX.ActiveXComponent;import .Dispatch;import .Variant;import Thread;public class WordObj{public WordObj(){}private static WordObj instance;private Dispatch doc = null;private Dispatch activeWindow = null;private Dispatch docSelection = null;private Dispatch wrdDocs = null;private String fileName;private ActiveXComponent wrdCom;/*** 获取Word操作静态实例对象** @return 报表汇总业务操作*/public final static synchronized WordObj getInstance()if (instance == null)instance = new WordObj();return instance;}/*** 初始化Word对象** @return 是否初始化成功*/public boolean initWordObj(){boolean retFlag = false;ComThread.InitSTA();// 初始化com的线程,非常重要!!使用结束后要调用 realease方法wrdCom = new ActiveXComponent("Word.Application");try{// 返回wrdCom.Documents的DispatchwrdDocs = wrdCom.getProperty("Documents").toDispatch();wrdCom.setProperty("Visible", new Variant(true));retFlag = true;}catch (Exception e){retFlag = false;e.printStackTrace();}return retFlag;}/*** 创建一个新的word文档**/public void createNewDocument(){doc = Dispatch.call(wrdDocs, "Add").toDispatch();docSelection = Dispatch.get(wrdCom, "Selection").toDispatch(); }* 取得活动窗体对象**/public void getActiveWindow(){// 取得活动窗体对象activeWindow = wrdCom.getProperty("ActiveWindow").toDispatch();}/*** 打开一个已存在的文档** @param docPath*/public void openDocument(String docPath){if (this.doc != null){this.closeDocument();}doc = Dispatch.call(wrdDocs, "Open", docPath).toDispatch();docSelection = Dispatch.get(wrdCom, "Selection").toDispatch(); }/*** 关闭当前word文档**/public void closeDocument(){if (doc != null){Dispatch.call(doc, "Save");Dispatch.call(doc, "Close", new Variant(0));doc = null;}}/*** 文档设置水印** @param waterMarkStr 水印字符串public void setWaterMark(String waterMarkStr){// 取得活动窗格对象Dispatch activePan = Dispatch.get(activeWindow, "ActivePane").toDispatch();// 取得视窗对象Dispatch view = Dispatch.get(activePan, "View").toDispatch();//输入页眉内容Dispatch.put(view, "SeekView", new Variant(9));Dispatch headfooter = Dispatch.get(docSelection, "HeaderFooter") .toDispatch();//取得图形对象Dispatch shapes = Dispatch.get(headfooter, "Shapes").toDispatch(); //给文档全部加上水印Dispatch selection = Dispatch.call(shapes, "AddTextEffect",new Variant(9), waterMarkStr, "宋体", new Variant(1),new Variant(false), new Variant(false), new Variant(0),new Variant(0)).toDispatch();Dispatch.call(selection, "Select");//设置水印参数Dispatch shapeRange = Dispatch.get(docSelection, "ShapeRange") .toDispatch();Dispatch.put(shapeRange, "Name", "PowerPlusWaterMarkObject1"); Dispatch textEffect =Dispatch.get(shapeRange,"TextEffect").toDispatch();Dispatch.put(textEffect, "NormalizedHeight", new Boolean(false)); Dispatch line = Dispatch.get(shapeRange, "Line").toDispatch(); Dispatch.put(line, "Visible", new Boolean(false));Dispatch fill = Dispatch.get(shapeRange, "Fill").toDispatch(); Dispatch.put(fill, "Visible", new Boolean(true));//设置水印透明度Dispatch.put(fill, "Transparency", new Variant(0.5));Dispatch foreColor =Dispatch.get(fill,"ForeColor").toDispatch();//设置水印颜色Dispatch.put(foreColor, "RGB", new Variant(16711680));Dispatch.call(fill, "Solid");//设置水印旋转Dispatch.put(shapeRange, "Rotation", new Variant(315));Dispatch.put(shapeRange, "LockAspectRatio", new Boolean(true)); Dispatch.put(shapeRange, "Height", new Variant(117.0709));Dispatch.put(shapeRange, "Width", new Variant(468.2835));Dispatch.put(shapeRange, "Left", new Variant(-999995));Dispatch.put(shapeRange, "Top", new Variant(-999995));Dispatch wrapFormat = Dispatch.get(shapeRange, "WrapFormat").toDispatch();//是否允许交叠Dispatch.put(wrapFormat, "AllowOverlap", new Variant(true)); Dispatch.put(wrapFormat, "Side", new Variant(3));Dispatch.put(wrapFormat, "Type", new Variant(3));Dispatch.put(shapeRange, "RelativeHorizontalPosition", new Variant(0));Dispatch.put(shapeRange, "RelativeVerticalPosition", new Variant(0));Dispatch.put(view, "SeekView", new Variant(0));}/*** 关闭Word资源***/public void closeWordObj(){// 关闭word文件wrdCom.invoke("Quit", new Variant[] {});// 释放com线程。
基于JACOB的Java通用WordWriter组件设计

( 州轻 工 业学 院 应 急管理 信 息技 术研 发 中心 ,河 南 郑 州 4 00 ) 郑 50 2 摘 要 : 了 O 易于操 作 Wod文 档 , 用 C S r 采 B D的 开发 思路 , 用 利 组件 重组技 术 , 计 并 实现 了基 于 J C B 的 Jv 用 Wod ir 设 A O aa通 rWre 组件 . t 通过 该 组 件使 用 Jv 言 aa语 可 以方便 地 生成各 种格 式 的 w0d文件 , 程 序 更 易读 、 r 使 易维 护 , 而缩 短 软 件 开发 周期 , 从 降低 开发
成本 .
关 键词 : O 组 件 ; rWre 组件 ;A O Jv ; B D CM Wod i r t J C B;aa C S
中图分 类 号 :P 1 . T 3 15
文 献标 志码 : A
Dein o a a g n r lW o d rtrc m p n n a e n J sg fJ v e e a r W i o o e tb s d o ACOB e
n n s d sg e sn BS d a a d c mp n n e o i a in t c n l g . h s c mp n n a a i et wa e in d u i g C D i e n o o e tr c mb n t e h oo y T i o o e tc n e sl o y g n r t a o s w r o u n sfr t.I d i o e e ae v r u o d d c me t oma s n a d t n,i ma e h r g a mo e r a a l ,e s o man i i t k st e p o r m r e d b e a y t i - ti n h  ̄e h o t r e e o me t y l n e u e d v l p n o t. an a d s o n t e s f wa e d v lp n ce a d r d c e eo me tc s c s
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
目录第一部分Word文档自动追加表格内容 (2)第二部分java jacob 操作word 文档,进行写操作,如生成表格,添加图片 (3)第三部分 (28)第一部分Word文档自动追加表格内容今天在做一个自动化生成SDD文档的小工具,通过Word的模板,前台通过Flex填入数据,最后将Word文档填写好。
以下是一部分代码,关于表格自动追加表格内容Java代码第二部分java jacob 操作word 文档,进行写操作,如生成表格,添加图片jacob-1.15-M3.zipjacob-1.15-M3-x86.dll copy到c://windows/system32引入jacob.jar 示例代码view p lainimport jav a.io.File;import com.jacob.activ eX.Activ eXComponent;import .Dispatch;import .Variant;class WordBean {// 代表一个word 程序priv ate Activ eXComponent MsWordApp = null;// 代表进行处理的word 文档priv ate Dispatch document = null;public WordBean() {// Open Word if we/'v e not done it alreadyif (MsWordApp == null) {MsWordApp = new Activ eXComponent("Word.Application");}}// 设置是否在前台打开word 程序,public v oid setVisible(boolean v isible) {MsWordApp.setProperty("Visible", new Variant(v isible));// 这一句作用相同// Dispatch.put(MsWordApp, "Visible", new Variant(v isible));}// 创建一个新文档public v oid createNewDocument() {// Find the Documents collection object maintained by Word// documents表示word的所有文档窗口,(word是多文档应用程序)Dispatch documents = Dispatch.get(MsWordApp, "Documents").toDispatch();// Call the Add method of the Documents collection to create// a new document to editdocument = Dispatch.call(documents, "Add").toDispatch();}// 打开一个存在的word文档,并用document 引用引用它public v oid openFile(String wordFilePath) {// Find the Documents collection object maintained by Word// documents表示word的所有文档窗口,(word是多文档应用程序)Dispatch documents = Dispatch.get(MsWordApp, "Documents").toDispatch();document = Dispatch.call(documents, "Open", wordFilePath,new Variant(true)/* 是否进行转换Conf irmConv ersions */,new Variant(f alse)/* 是否只读*/).toDispatch();// document = Dispatch.inv oke(documents, "Open", Dispatch.Method,// new Object[] { wordFilePath, new Variant(true),// new Variant(f alse)// }, new int[1]).toDispatch();}// 向document 中插入文本内容public v oid insertText(String textToInsert) {// Get the current selection within Word at the moment.// a new document has just been created then this will be at// the top of the new doc 获得选中的内容,如果是一个新创建的文件,因里面无内容,则光标应处于文件开头处Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch();// 取消选中,应该就是移动光标,否则新添加的内容会覆盖选中的内容Dispatch.call(selection, "Mov eRight", new Variant(1), new Variant(1));// Put the specified text at the insertion pointDispatch.put(selection, "Text", textToInsert);// 取消选中,应该就是移动光标Dispatch.call(selection, "Mov eRight", new Variant(1), new Variant(1));}// 向文档中添加一个图片,public v oid insertJpeg(String jpegFilePath) {Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch();Dispatch image = Dispatch.get(selection, "InLineShapes").toDispatch();Dispatch.call(image, "AddPicture", jpegFilePath);}// 段落的处理,插入格式化的文本public v oid insertFormatStr(String text) {Dispatch wordContent = Dispatch.get(document, "Content").toDispatch(); // 取得word文件的内容Dispatch.call(wordContent, "InsertAfter", text);// 插入一个段落到最后Dispatch paragraphs = Dispatch.get(wordContent, "Paragraphs").toDispatch(); // 所有段落int paragraphCount = Dispatch.get(paragraphs, "Count").changeTy pe(Variant.VariantInt).getInt();// 一共的段落数// 找到刚输入的段落,设置格式Dispatch lastParagraph = Dispatch.call(paragraphs, "Item",new Variant(paragraphCount)).toDispatch(); // 最后一段(也就是刚插入的)// Range 对象表示文档中的一个连续范围,由一个起始字符位置和一个终止字符位置定义Dispatch lastParagraphRange = Dispatch.get(lastParagraph, "Range").toDispatch();Dispatch f ont = Dispatch.get(lastParagraphRange, "Font").toDispatch();Dispatch.put(f ont, "Bold", new Variant(true)); // 设置为黑体Dispatch.put(f ont, "Italic", new Variant(true)); // 设置为斜体Dispatch.put(f ont, "Name", new Variant("宋体")); //Dispatch.put(f ont, "Size", new Variant(12)); // 小四Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch();Dispatch.call(selection, "Ty peParagraph");// 插入一个空行Dispatch alignment = Dispatch.get(selection, "ParagraphFormat").toDispatch();// 段落格式Dispatch.put(alignment, "Alignment", "2"); // (1:置中2:靠右3:靠左)}// word 中在对表格进行遍历的时候,是先列后行先column 后cell// 另外下标从1开始public v oid insertTable(String tableTitle, int row, int column) {Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch(); // 输入内容需要的对象Dispatch.call(selection, "Ty peText", tableTitle); // 写入标题内容// 标题格行Dispatch.call(selection, "Ty peParagraph"); // 空一行段落Dispatch.call(selection, "Ty peParagraph"); // 空一行段落Dispatch.call(selection, "Mov eDown"); // 游标往下一行// 建立表格Dispatch tables = Dispatch.get(document, "Tables").toDispatch();// int count = Dispatch.get(tables,// "Count").changeTy pe(Variant.VariantInt).getInt(); // document中的表格数量// Dispatch table = Dispatch.call(tables, "Item", new Variant(// 1)).toDispatch();//文档中第一个表格Dispatch range = Dispatch.get(selection, "Range").toDispatch();// /当前光标位置或者选中的区域Dispatch newTable = Dispatch.call(tables, "Add", range,new Variant(row), new Variant(column), new Variant(1)).toDispatch(); // 设置row,column,表格外框宽度Dispatch cols = Dispatch.get(newTable, "Columns").toDispatch(); // 此表的所有列,int colCount = Dispatch.get(cols, "Count").changeTy pe(Variant.VariantInt).getInt();// 一共有多少列实际上这个数==columnSystem.out.println(colCount + "列");f or (int i = 1; i <= colCount; i++) { // 循环取出每一列Dispatch col = Dispatch.call(cols, "Item", new Variant(i)).toDispatch();Dispatch cells = Dispatch.get(col, "Cells").toDispatch();// 当前列中单元格int cellCount = Dispatch.get(cells, "Count").changeTy pe(Variant.VariantInt).getInt();// 当前列中单元格数实际上这个数等于rowf or (int j = 1; j <= cellCount; j++) {// 每一列中的单元格数// Dispatch cell = Dispatch.call(cells, "Item", new// Variant(j)).toDispatch(); //当前单元格// Dispatch cell = Dispatch.call(newTable, "Cell", new// Variant(j) , new Variant(i) ).toDispatch(); //取单元格的另一种方法// Dispatch.call(cell, "Select");//选中当前单元格// Dispatch.put(selection, "Text",// "第"+j+"行,第"+i+"列");//往选中的区域中填值,也就是往当前单元格填值putTxtToCell(newTable, j, i, "第" + j + "行,第" + i + "列");// 与上面四句的作用相同}}}/** *//*** 在指定的单元格里填写数据** @param tableIndex* @param cellRowIdx* @param cellColIdx* @param txt*/public v oid putTxtToCell(Dispatch table, int cellRowIdx, int cellColIdx,String txt) {Dispatch cell = Dispatch.call(table, "Cell", new Variant(cellRowIdx),new Variant(cellColIdx)).toDispatch();Dispatch.call(cell, "Select");Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch(); // 输入内容需要的对象Dispatch.put(selection, "Text", txt);}/** *//*** 在指定的单元格里填写数据** @param tableIndex* @param cellRowIdx* @param cellColIdx* @param txt*/public v oid putTxtToCell(int tableIndex, int cellRowIdx, int cellColIdx,String txt) {// 所有表格Dispatch tables = Dispatch.get(document, "Tables").toDispatch();// 要填充的表格Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex)).toDispatch();Dispatch cell = Dispatch.call(table, "Cell", new Variant(cellRowIdx),new Variant(cellColIdx)).toDispatch();Dispatch.call(cell, "Select");Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch(); // 输入内容需要的对象Dispatch.put(selection, "Text", txt);}// 合并两个单元格public v oid mergeCell(Dispatch cell1, Dispatch cell2) {Dispatch.call(cell1, "Merge", cell2);}public v oid mergeCell(Dispatch table, int row1, int col1, int row2, int col2) {Dispatch cell1 = Dispatch.call(table, "Cell", new Variant(row1),new Variant(col1)).toDispatch();Dispatch cell2 = Dispatch.call(table, "Cell", new Variant(row2),new Variant(col2)).toDispatch();mergeCell(cell1, cell2);}public v oid mergeCellTest() {Dispatch tables = Dispatch.get(document, "Tables").toDispatch();int tableCount = Dispatch.get(tables, "Count").changeTy pe(Variant.VariantInt).getInt(); // document中的表格数量Dispatch table = Dispatch.call(tables, "Item", new Variant(tableCount)).toDispatch();// 文档中最后一个tablemergeCell(table, 1, 1, 1, 2);// 将table 中x=1,y=1 与x=1,y=2的两个单元格合并}// ========================================================/** *//*** 把选定的内容或光标插入点向上移动** @param pos* 移动的距离*/public v oid mov eUp(int pos) {Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch(); // 输入内容需要的对象f or (int i = 0; i < pos; i++) {// Mov eDown Mov eLef t mov eRight// mov eStart ( Dispatch.call(selection, "HomeKey", new Variant(6));// )// mov eEnd Dispatch.call(selection, "EndKey", new Variant(6));Dispatch.call(selection, "Mov eUp");}}/** *//*** 从选定内容或插入点开始查找文本** @param toFindText* 要查找的文本* @return boolean true-查找到并选中该文本,f alse-未查找到文本*/public boolean f ind(String toFindText) {if (toFindText == null || toFindText.equals(""))return f alse;Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch(); // 输入内容需要的对象// 从selection所在位置开始查询Dispatch find = Dispatch.call(selection, "Find").toDispatch();// 设置要查找的内容Dispatch.put(f ind, "Text", toFindText);// 向前查找Dispatch.put(f ind, "Forward", "True");// 设置格式Dispatch.put(f ind, "Format", "True");// 大小写匹配Dispatch.put(f ind, "MatchCase", "True");// 全字匹配Dispatch.put(f ind, "MatchWholeWord", "True");// 查找并选中return Dispatch.call(f ind, "Execute").getBoolean();}/** *//*** 把选定选定内容设定为替换文本** @param toFindText* 查找字符串* @param newText* 要替换的内容* @return*/public boolean replaceText(String toFindText, String newText) {if (!f ind(toFindText))return f alse;Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch(); // 输入内容需要的对象Dispatch.put(selection, "Text", newText);return true;}public v oid printFile() {// Just print the current document to the def ault printer Dispatch.call(document, "PrintOut");}// 保存文档的更改public v oid sav e() {Dispatch.call(document, "Sav e");}public v oid sav eFileAs(String f ilename) {Dispatch.call(document, "Sav eAs", f ilename);}public v oid closeDocument() {// Close the document without sav ing changes// 0 = wdDoNotSav eChanges// -1 = wdSav eChanges// -2 = wdPromptToSav eChangesDispatch.call(document, "Close", new Variant(0));document = null;}public v oid closeWord() {Dispatch.call(MsWordApp, "Quit");MsWordApp = null;document = null;}// 设置wordApp打开后窗口的位置public v oid setLocation() {Dispatch activ eWindow = Dispatch.get(MsWordApp, "Application") .toDispatch();Dispatch.put(activ eWindow, "WindowState", new Variant(1)); // 0=def ault // 1=maximize// 2=minimizeDispatch.put(activ eWindow, "Top", new Variant(0));Dispatch.put(activ eWindow, "Lef t", new Variant(0));Dispatch.put(activ eWindow, "Height", new Variant(600));Dispatch.put(activ eWindow, "width", new Variant(800));}}public class JacobTest2 {public static v oid createANewFileTest() {WordBean wordBean = new WordBean();// word.openWord(true);// 打开word 程序wordBean.setVisible(true);wordBean.createNewDocument();// 创建一个新文档wordBean.setLocation();// 设置打开后窗口的位置wordBean.insertText("你好");// 向文档中插入字符wordBean.insertJpeg("D:" + File.separator + "a.jpg"); // 插入图片// 如果,想保存文件,下面三句// word.sav eFileAs("d://a.doc");// word.closeDocument();// word.closeWord();}public static v oid openAnExistsFileTest() {WordBean wordBean = new WordBean();wordBean.setVisible(true); // 是否前台打开word 程序,或者后台运行wordBean.openFile("d://a.doc");wordBean.insertJpeg("D:" + File.separator + "a.jpg"); // 插入图片(注意刚打开的word // ,光标处于开头,故,图片在最前方插入)wordBean.sav e();wordBean.closeDocument();wordBean.closeWord();}public static v oid insertFormatStr(String str) {WordBean wordBean = new WordBean();wordBean.setVisible(true); // 是否前台打开word 程序,或者后台运行wordBean.createNewDocument();// 创建一个新文档wordBean.insertFormatStr(str);// 插入一个段落,对其中的字体进行了设置}public static v oid insertTableTest() {WordBean wordBean = new WordBean();wordBean.setVisible(true); // 是否前台打开word 程序,或者后台运行wordBean.createNewDocument();// 创建一个新文档wordBean.setLocation();wordBean.insertTable("表名", 3, 2);wordBean.sav eFileAs("d://table.doc");wordBean.closeDocument();wordBean.closeWord();}public static v oid mergeTableCellTest() {insertTableTest();//生成d://table.docWordBean wordBean = new WordBean();wordBean.setVisible(true); // 是否前台打开word 程序,或者后台运行wordBean.openFile("d://table.doc");wordBean.mergeCellTest();}public static v oid main(String[] args) {// 进行测试前要保证d://a.jpg 图片文件存在// createANewFileTest();//创建一个新文件// openAnExistsFileTest();// 打开一个存在的文件// insertFormatStr("格式化字符串");//对字符串进行一定的修饰//insertTableTest();// 创建一个表格mergeTableCellTest();// 对表格中的单元格进行合并}}第三部分jav a写入word表格模板(欢迎高手过来探讨)我有一份word表格模板,格式是规定的了数据是从数据库读出来的,现在想把读出来的数据插入到模板的相应位置大家有什么好建议吗??我知道用jacod组件可以,但是jacod效率太低,大家如果有其他好的方法,麻烦提供一下,谢谢!问题补充:Barry Wei有没有Demo呢??有的话可以发给我吗??f alcon1990是利用poi对excel表格操作,这个我也会啊,我要的是对word的表格问题补充:jav a 下的该问题已经关闭: 既然大家都没有什么好点的方法,我只能去操作2007的XML啦,推荐一篇文章给大家http://www.inf /cn/articles/cracking-office-2007-with-jav a回答首先,在word模板中适当的位置处加上特殊标记,比如$内容$。