java jacob 操作word 文档
- 格式:doc
- 大小:127.00 KB
- 文档页数:17
龙源期刊网
基于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作为开发工具良好的可扩展性。
用Java读取Word文档由于Word的编码方式比较复杂,所以Word文档不可能通过流的方式直接读取;当然如果Word可以转化成TXT文件就可以直接读取了;目前读取Word比较好的开源工具是Poi及Jacob,感觉Poi读取功能要比Jacob略逊一筹,毕竟Jacob可以直接调用Word的COM组件;但是微软产品不开放源码,所以Jacob读取Word文档也只能是摸着石头过河,一点一点破解了。
Jacob读取Word内容,由于Word内容的复杂性,读取也是非常不方便的,目前可以有"按段落读取","按书签读取"及"按照表格读取"等几种形式。
示例讲解(通过Java FileReader,Jacob两种方式读取Word内容)一.通过java流读取Word内容复制代码1.import java.io.BufferedReader;2.import java.io.FileReader;3.import java.io.IOException;4.5.public class ReadWordByStream {6.public static void main(String[] args) throws IOException {7. String rowContent = new String();8. String content = new String();9. BufferedReader in = new BufferedReader(new FileReader("d:\\test3.doc"));10. while ((rowContent = in.readLine()) != null) {11.content = content + rowContent + "\n";12. }13. System.out.println(content.getBytes());14. System.out.println(new String(content.getBytes(),"utf-8"));//因为编码方式不同,不容易解析15. in.close();16.}17.18.}二.通过Jacob读取Word内容复制代码1.import com.jacob.activeX.ActiveXComponent;2.import Thread;3.import .Dispatch;4.import .Variant;5.6.public class WordReader {7.public static void main(String args[]) {8. ComThread.InitSTA();// 初始化com的线程9. ActiveXComponent wordApp = new ActiveXComponent("Word.Application"); // 启动word10. // Set the visible property as required.11. Dispatch.put(wordApp, "Visible", new Variant(true));// //设置word可见12. Dispatch docs = wordApp.getProperty("Documents").toDispatch();//所有文档窗口13.// String inFile = "d:\\test.doc";14.// Dispatch doc = Dispatch.invoke(docs,"Open",Dispatch.Method,15.// new Object[] { inFile, new Variant(false),new Variant(false) },//参数3,false:可写,true:只读16.// new int[1]).toDispatch();//打开文档17.18. Dispatch doc = Dispatch.call(docs, "Add").toDispatch(); //创建一个新文档19. Dispatch wordContent = Dispatch.get(doc, "Content").toDispatch(); //取得word文件的内容20. Dispatch font = Dispatch.get(wordContent, "Font").toDispatch();21. Dispatch.put(font, "Bold", new Variant(true)); // 设置为粗体22.Dispatch.put(font, "Italic", new Variant(true)); // 设置为斜体23.Dispatch.put(font, "Underline", new Variant(true));24.Dispatch.put(font, "Name", new Variant("宋体"));25.Dispatch.put(font, "Size", new Variant(14));26. for(int i=0;i<10;i++){//作为一个段落27.Dispatch.call(wordContent, "InsertAfter", "current paragraph"+i+" ");28. }29. for(int j=0;j<10;j++){//作为十个段落30. Dispatch.call(wordContent, "InsertAfter", "current paragraph"+j+"\r");31.}32. Dispatch paragraphs = Dispatch.get(wordContent, "Paragraphs")33. .toDispatch(); //所有段落34. int paragraphCount = Dispatch.get(paragraphs, "Count").getInt();35. System.out.println("paragraphCount:"+paragraphCount);36.37. for (int i = 1; i <= paragraphCount; i++) {38.Dispatch paragraph = Dispatch.call(paragraphs, "Item",39.new Variant(i)).toDispatch();40.Dispatch paragraphRange = Dispatch.get(paragraph, "Range")41..toDispatch();42.String paragraphContent = Dispatch.get(paragraphRange, "Text")43..toString();44.System.out.println(paragraphContent);45.//Dispatch.call(selection, "MoveDown");46. }47. // WordReader.class.getClass().getResource("/").getPath().substring+"test.doc";48. Dispatch.call(doc, "SaveAs","d:\\wordreader.doc");49. // Close the document without saving changes50. // 0 = wdDoNotSaveChanges51. // -1 = wdSaveChanges52. // -2 = wdPromptToSaveChanges53. ComThread.Release();//释放com线程54. Dispatch.call(docs, "Close", new Variant(0));55. docs = null;56. Dispatch.call(wordApp,"Quit");57. wordApp = null;58.}59.}用Java简单的读取word文档中的数据:第一步:下载tm-extractors-0.4.jar下载地址:/browser/elated-core/trunk/lib/tm-extractors-0.4.jar?rev =46并把它放到你的classpath路径下面。
通过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文档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实现⽂档格式转换实现⽂档格式之间的转换,我使⽤的是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详细教程博客分类: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⽂件将⼏个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。
java⽣成word的⼏种⽅案1、 Jacob是Java-COM Bridge的缩写,它在Java与微软的COM组件之间构建⼀座桥梁。
使⽤Jacob⾃带的DLL动态链接库,并通过JNI的⽅式实现了在Java平台上对COM程序的调⽤。
DLL动态链接库的⽣成需要windows平台的⽀持。
2、 Apache POI包括⼀系列的API,它们可以操作基于MicroSoft OLE 2 Compound Document Format的各种格式⽂件,可以通过这些API在Java中读写Excel、Word等⽂件。
他的excel处理很强⼤,对于word还局限于读取,⽬前只能实现⼀些简单⽂件的操作,不能设置样式。
3、 Java2word是⼀个在java程序中调⽤ MS Office Word ⽂档的组件(类库)。
该组件提供了⼀组简单的接⼝,以便java程序调⽤他的服务操作Word ⽂档。
这些服务包括:打开⽂档、新建⽂档、查找⽂字、替换⽂字,插⼊⽂字、插⼊图⽚、插⼊表格,在书签处插⼊⽂字、插⼊图⽚、插⼊表格等。
填充数据到表格中读取表格数据,1.1版增强的功能:指定⽂本样式,指定表格样式。
如此,则可动态排版word⽂档。
4、 iText操作Excel还⾏。
对于复杂的⼤量的word也是噩梦。
⽤法很简单, 但是功能很少, 不能设置打印⽅向等问题。
5、 JSP输出样式基本不达标,⽽且要打印出来就更是惨不忍睹。
6、⽤XML做就很简单了。
Word从2003开始⽀持XML格式,⼤致的思路是先⽤office2003或者2007编辑好word的样式,然后另存为xml,将xml翻译为FreeMarker模板,最后⽤java来解析FreeMarker模板并输出Doc。
经测试这样⽅式⽣成的word⽂档完全符合office标准,样式、内容控制⾮常便利,打印也不会变形,⽣成的⽂档和office中编辑⽂档完全⼀样。
7、补充⼀种⽅案,可以⽤类似ueditor的在线编辑器编辑word⽂档,在将html⽂件转换为xhtml⽂件,再转换为word。
Java操作word⽂档使⽤JACOB和POI操作word,Excel,PPT需要的jar包可参考⽂档:下载jar包如上是jacob-1.17-M2.jar对应的jar包和dll⽂件....但是我在maven仓库中并没有发现jacob-1.17版本的.所以如果使⽤maven项⽬的话推荐下载jacob-1.14版本的jar包和dll⽂件.使⽤⽅式:import java.io.File;import java.io.FileInputStream;import java.util.ArrayList;import java.util.Arrays;import com.jacob.activeX.ActiveXComponent;public class WriteDoc2 {public static void main(String[] args) {//在正式批量跑之前,做单个word⽂档的测试.WordUtils util = new WordUtils(true);util.openDocument("C:\\Users\\ABC\\Desktop\\test.docx");util.setSaveOnExit(true);util.insertText("xxx444dddd4x");util.saveAs("C:\\Users\\ABC\\Desktop\\test.docx");util.closeDocument();}}对应WordUtils.java⼯具类,我是使⽤的如下:import com.jacob.activeX.ActiveXComponent;import .Dispatch;import .Variant;public class WordUtils {// word运⾏程序对象private ActiveXComponent word;// 所有word⽂档集合private Dispatch documents;// word⽂档private Dispatch doc;// 选定的范围或插⼊点private Dispatch selection;// 保存退出private boolean saveOnExit;public WordUtils(boolean visible) {word = new ActiveXComponent("Word.Application");word.setProperty("Visible", new Variant(visible));documents = word.getProperty("Documents").toDispatch();}/*** 设置退出时参数** @param saveOnExit* boolean true-退出时保存⽂件,false-退出时不保存⽂件 */public void setSaveOnExit(boolean saveOnExit) {this.saveOnExit = saveOnExit;}/*** 创建⼀个新的word⽂档*/public void createNewDocument() {doc = Dispatch.call(documents, "Add").toDispatch();selection = Dispatch.get(word, "Selection").toDispatch();}/*** 打开⼀个已经存在的word⽂档** @param docPath*/public void openDocument(String docPath) {doc = Dispatch.call(documents, "Open", docPath).toDispatch();selection = Dispatch.get(word, "Selection").toDispatch();}/*** 打开⼀个有密码保护的word⽂档* @param docPath* @param password*/public void openDocument(String docPath, String password) {doc = Dispatch.call(documents, "Open", docPath).toDispatch();unProtect(password);selection = Dispatch.get(word, "Selection").toDispatch();}/*** 去掉密码保护* @param password*/public void unProtect(String password){try{String protectionType = Dispatch.get(doc, "ProtectionType").toString();if(!"-1".equals(protectionType)){Dispatch.call(doc, "Unprotect", password);}}catch(Exception e){e.printStackTrace();}}/*** 添加密码保护* @param password*/public void protect(String password){String protectionType = Dispatch.get(doc, "ProtectionType").toString();if("-1".equals(protectionType)){Dispatch.call(doc, "Protect",new Object[]{new Variant(3), new Variant(true), password});}}/*** 显⽰审阅的最终状态*/public void showFinalState(){Dispatch.call(doc, "AcceptAllRevisionsShown");}/*** 打印预览:*/public void printpreview() {Dispatch.call(doc, "PrintPreView");}/*** 打印*/public void print(){Dispatch.call(doc, "PrintOut");}public void print(String printerName) {word.setProperty("ActivePrinter", new Variant(printerName));print();}/*** 指定打印机名称和打印输出⼯作名称* @param printerName* @param outputName*/public void print(String printerName, String outputName){word.setProperty("ActivePrinter", new Variant(printerName));Dispatch.call(doc, "PrintOut", new Variant[]{new Variant(false), new Variant(false), new Variant(0), new Variant(outputName)}); }/*** 把选定的内容或插⼊点向上移动** @param pos*/public void moveUp(int pos) {move("MoveUp", pos);}/*** 把选定的内容或者插⼊点向下移动** @param pos*/public void moveDown(int pos) {move("MoveDown", pos);}/*** 把选定的内容或者插⼊点向左移动** @param pos*/public void moveLeft(int pos) {move("MoveLeft", pos);}/*** 把选定的内容或者插⼊点向右移动** @param pos*/public void moveRight(int pos) {move("MoveRight", pos);}/*** 把选定的内容或者插⼊点向右移动*/public void moveRight() {Dispatch.call(getSelection(), "MoveRight");}/*** 把选定的内容或者插⼊点向指定的⽅向移动* @param actionName* @param pos*/private void move(String actionName, int pos) {for (int i = 0; i < pos; i++)Dispatch.call(getSelection(), actionName);}/*** 把插⼊点移动到⽂件⾸位置*/public void moveStart(){Dispatch.call(getSelection(), "HomeKey", new Variant(6));}/*** 把插⼊点移动到⽂件末尾位置*/public void moveEnd(){Dispatch.call(getSelection(), "EndKey", new Variant(6));}/*** 插⼊换页符*/public void newPage(){Dispatch.call(getSelection(), "InsertBreak");}public void nextPage(){moveEnd();moveDown(1);}public int getPageCount(){Dispatch selection = Dispatch.get(word, "Selection").toDispatch();return Dispatch.call(selection,"information", new Variant(4)).getInt(); }/*** 获取当前的选定的内容或者插⼊点* @return当前的选定的内容或者插⼊点*/public Dispatch getSelection(){if (selection == null)selection = Dispatch.get(word, "Selection").toDispatch();return selection;}/*** 从选定内容或插⼊点开始查找⽂本* @param findText 要查找的⽂本* @return boolean true-查找到并选中该⽂本,false-未查找到⽂本*/public boolean find(String findText){if(findText == null || findText.equals("")){return false;}// 从selection所在位置开始查询Dispatch find = Dispatch.call(getSelection(), "Find").toDispatch();// 设置要查找的内容Dispatch.put(find, "Text", findText);// 向前查找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 findText* @param newText* @return boolean true-查找到并替换该⽂本,false-未查找到⽂本*/public boolean replaceText(String findText, String newText){moveStart();if (!find(findText))return false;Dispatch.put(getSelection(), "Text", newText);return true;}/*** 进⼊页眉视图*/public void headerView(){//取得活动窗体对象Dispatch ActiveWindow = word.getProperty( "ActiveWindow").toDispatch();//取得活动窗格对象Dispatch ActivePane = Dispatch.get(ActiveWindow, "ActivePane").toDispatch();//取得视窗对象Dispatch view = Dispatch.get(ActivePane, "View").toDispatch();Dispatch.put(view, "SeekView", "9");}/*** 进⼊页脚视图*/public void footerView(){//取得活动窗体对象Dispatch ActiveWindow = word.getProperty( "ActiveWindow").toDispatch();//取得活动窗格对象Dispatch ActivePane = Dispatch.get(ActiveWindow, "ActivePane").toDispatch();//取得视窗对象Dispatch view = Dispatch.get(ActivePane, "View").toDispatch();Dispatch.put(view, "SeekView", "10");}/*** 进⼊普通视图*/public void pageView(){//取得活动窗体对象Dispatch ActiveWindow = word.getProperty( "ActiveWindow").toDispatch();//取得活动窗格对象Dispatch ActivePane = Dispatch.get(ActiveWindow, "ActivePane").toDispatch();//取得视窗对象Dispatch view = Dispatch.get(ActivePane, "View").toDispatch();Dispatch.put(view, "SeekView", new Variant(0));//普通视图}/*** 全局替换⽂本* @param findText* @param newText*/public void replaceAllText(String findText, String newText){int count = getPageCount();for(int i = 0; i < count; i++){headerView();while (find(findText)){Dispatch.put(getSelection(), "Text", newText);moveEnd();}footerView();while (find(findText)){Dispatch.put(getSelection(), "Text", newText);moveStart();}pageView();moveStart();while (find(findText)){Dispatch.put(getSelection(), "Text", newText);moveStart();}nextPage();}}/*** 全局替换⽂本* @param findText* @param newText*/public void replaceAllText(String findText, String newText, String fontName, int size){ /****插⼊页眉页脚*****///取得活动窗体对象Dispatch ActiveWindow = word.getProperty( "ActiveWindow").toDispatch();//取得活动窗格对象Dispatch ActivePane = Dispatch.get(ActiveWindow, "ActivePane").toDispatch();//取得视窗对象Dispatch view = Dispatch.get(ActivePane, "View").toDispatch();/****设置页眉*****/Dispatch.put(view, "SeekView", "9");while (find(findText)){Dispatch.put(getSelection(), "Text", newText);moveStart();}/****设置页脚*****/Dispatch.put(view, "SeekView", "10");while (find(findText)){Dispatch.put(getSelection(), "Text", newText);moveStart();}Dispatch.put(view, "SeekView", new Variant(0));//恢复视图moveStart();while (find(findText)){Dispatch.put(getSelection(), "Text", newText);putFontSize(getSelection(), fontName, size);moveStart();}}/*** 设置选中或当前插⼊点的字体* @param selection* @param fontName* @param size*/public void putFontSize(Dispatch selection, String fontName, int size){Dispatch font = Dispatch.get(selection, "Font").toDispatch();Dispatch.put(font, "Name", new Variant(fontName));Dispatch.put(font, "Size", new Variant(size));}/*** 在当前插⼊点插⼊字符串*/public void insertText(String text){Dispatch.put(getSelection(), "Text", text);}/*** 将指定的⽂本替换成图⽚* @param findText* @param imagePath* @return boolean true-查找到并替换该⽂本,false-未查找到⽂本*/public boolean replaceImage(String findText, String imagePath, int width, int height){moveStart();if (!find(findText))return false;Dispatch picture = Dispatch.call(Dispatch.get(getSelection(), "InLineShapes").toDispatch(), "AddPicture", imagePath).toDispatch(); Dispatch.call(picture, "Select");Dispatch.put(picture, "Width", new Variant(width));Dispatch.put(picture, "Height", new Variant(height));moveRight();return true;}/*** 全局将指定的⽂本替换成图⽚* @param findText* @param imagePath*/public void replaceAllImage(String findText, String imagePath, int width, int height){moveStart();while (find(findText)){Dispatch picture = Dispatch.call(Dispatch.get(getSelection(), "InLineShapes").toDispatch(), "AddPicture", imagePath).toDispatch(); Dispatch.call(picture, "Select");Dispatch.put(picture, "Width", new Variant(width));Dispatch.put(picture, "Height", new Variant(height));moveStart();}}/*** 在当前插⼊点中插⼊图⽚* @param imagePath*/public void insertImage(String imagePath, int width, int height){Dispatch picture = Dispatch.call(Dispatch.get(getSelection(), "InLineShapes").toDispatch(), "AddPicture", imagePath).toDispatch(); Dispatch.call(picture, "Select");Dispatch.put(picture, "Width", new Variant(width));Dispatch.put(picture, "Height", new Variant(height));moveRight();}/*** 在当前插⼊点中插⼊图⽚* @param imagePath*/public void insertImage(String imagePath){Dispatch.call(Dispatch.get(getSelection(), "InLineShapes").toDispatch(), "AddPicture", imagePath);}/*** 获取书签的位置* @param bookmarkName* @return书签的位置*/public Dispatch getBookmark(String bookmarkName){try{Dispatch bookmark = Dispatch.call(this.doc, "Bookmarks", bookmarkName).toDispatch();return Dispatch.get(bookmark, "Range").toDispatch();}catch(Exception e){e.printStackTrace();}return null;}/*** 在指定的书签位置插⼊图⽚* @param bookmarkName* @param imagePath*/public void insertImageAtBookmark(String bookmarkName, String imagePath){Dispatch dispatch = getBookmark(bookmarkName);if(dispatch != null)Dispatch.call(Dispatch.get(dispatch, "InLineShapes").toDispatch(), "AddPicture", imagePath);}/*** 在指定的书签位置插⼊图⽚* @param bookmarkName* @param imagePath* @param width* @param height*/public void insertImageAtBookmark(String bookmarkName, String imagePath, int width, int height){Dispatch dispatch = getBookmark(bookmarkName);if(dispatch != null){Dispatch picture = Dispatch.call(Dispatch.get(dispatch, "InLineShapes").toDispatch(), "AddPicture", imagePath).toDispatch();Dispatch.call(picture, "Select");Dispatch.put(picture, "Width", new Variant(width));Dispatch.put(picture, "Height", new Variant(height));}}/*** 在指定的书签位置插⼊⽂本* @param bookmarkName* @param text*/public void insertAtBookmark(String bookmarkName, String text){Dispatch dispatch = getBookmark(bookmarkName);if(dispatch != null)Dispatch.put(dispatch, "Text", text);}/*** ⽂档另存为* @param savePath*/public void saveAs(String savePath){Dispatch.call(doc, "SaveAs", savePath);}/*** ⽂档另存为PDF* <b><p>注意:此操作要求word是2007版本或以上版本且装有加载项:Microsoft Save as PDF 或 XPS</p></b>* @param savePath*/public void saveAsPdf(String savePath){Dispatch.call(doc, "SaveAs", new Variant(17));}/*** 保存⽂档* @param savePath*/public void save(String savePath){Dispatch.call(Dispatch.call(word, "WordBasic").getDispatch(),"FileSaveAs", savePath);}/*** 关闭word⽂档*/public void closeDocument(){if (doc != null) {Dispatch.call(doc, "Close", new Variant(saveOnExit));doc = null;}}public void exit(){word.invoke("Quit", new Variant[0]);}}具体WordUtils类的使⽤暂时没有看到更多的例⼦,上⾯的util的使⽤是⾃⼰摸索出来的,可能不是最优,最恰当的.//==================================================================================================使⽤Java⼯具POI操作MicroSoft Office套件Word,Excle和PPT使⽤Maven⼯程的话需要在Pom.xml⽂件中引⼊的jar包.⼀开始是想使⽤POI⼯具操作,但是从⽹上找来的代码始终报编译错误,代码中的⼀些类找不到,但是也明明已经引⼊了poi-3.x.jar包⽂件,更换了好⼏个poi版本的jar包仍是⼀样的效果.随后调查,到底需要哪些jar包.....结果如下:<dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>3.8</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>3.8</version></dependency><dependency><groupId>org.apache.xmlbeans</groupId><artifactId>xmlbeans</artifactId><version>2.3.0</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-scratchpad</artifactId><version>3.8</version></dependency>所依赖的全部jar包的截图如果只引⼊⼀个poi-3.x.jar包是会报错的. POI具体操作Word,Excel,和PPT的代码,⾃⾏百度.只要jar包引⼊的正确,运⾏编译代码就没有问题.。
java jacob 操作word 文档,进行写操作,如生成表格,添加图片jacob-1.15-M3.zipjacob-1.15-M3-x86.dll copy 到c:\\windows\system32引入jacob.jar示例代码import java.io.File;import com.jacob.activeX.ActiveXComponent;import .Dispatch;import .Variant;class WordBean {// 代表一个word 程序private ActiveXComponent MsWordApp = null;// 代表进行处理的word 文档private Dispatch document = null;public WordBean() {// Open Word if we\'ve not done it alreadyif (MsWordApp == null) {MsWordApp = new ActiveXComponent("Word.Application");}}// 设置是否在前台打开word 程序,public void setVisible(boolean visible) {MsWordApp.setProperty("Visible", new Variant(visible));// 这一句作用相同// Dispatch.put(MsWordApp, "Visible", new Variant(visible));}// 创建一个新文档public void 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 void 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 V ariant(true)/* 是否进行转换ConfirmConversions */,new V ariant(false)/* 是否只读*/).toDispatch();// document = Dispatch.invoke(documents, "Open", Dispatch.Method,// new Object[] { wordFilePath, new Variant(true),// new Variant(false)// }, new int[1]).toDispatch();}// 向document 中插入文本内容public void 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, "MoveRight", new Variant(1), new Variant(1));// Put the specified text at the insertion pointDispatch.put(selection, "Text", textToInsert);// 取消选中,应该就是移动光标Dispatch.call(selection, "MoveRight", new Variant(1), new Variant(1));}// 向文档中添加一个图片,public void insertJpeg(String jpegFilePath) {Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch();Dispatch image = Dispatch.get(selection, "InLineShapes").toDispatch();Dispatch.call(image, "AddPicture", jpegFilePath);}// 段落的处理,插入格式化的文本public void 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").changeType(V ariant.VariantInt).getInt();// 一共的段落数// 找到刚输入的段落,设置格式Dispatch lastParagraph = Dispatch.call(paragraphs, "Item",new V ariant(paragraphCount)).toDispatch(); // 最后一段(也就是刚插入的)// Range 对象表示文档中的一个连续范围,由一个起始字符位置和一个终止字符位置定义Dispatch lastParagraphRange = Dispatch.get(lastParagraph, "Range").toDispatch();Dispatch font = Dispatch.get(lastParagraphRange, "Font").toDispatch();Dispatch.put(font, "Bold", new Variant(true)); // 设置为黑体Dispatch.put(font, "Italic", new Variant(true)); // 设置为斜体Dispatch.put(font, "Name", new Variant("宋体")); //Dispatch.put(font, "Size", new Variant(12)); // 小四Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch();Dispatch.call(selection, "TypeParagraph");// 插入一个空行Dispatch alignment = Dispatch.get(selection, "ParagraphFormat").toDispatch();// 段落格式Dispatch.put(alignment, "Alignment", "2"); // (1:置中2:靠右3:靠左) }// word 中在对表格进行遍历的时候,是先列后行先column 后cell// 另外下标从1开始public void insertTable(String tableTitle, int row, int column) {Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch(); // 输入内容需要的对象Dispatch.call(selection, "TypeText", tableTitle); // 写入标题内容// 标题格行Dispatch.call(selection, "TypeParagraph"); // 空一行段落Dispatch.call(selection, "TypeParagraph"); // 空一行段落Dispatch.call(selection, "MoveDown"); // 游标往下一行// 建立表格Dispatch tables = Dispatch.get(document, "Tables").toDispatch();// int count = Dispatch.get(tables,// "Count").changeType(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 V ariant(row), new Variant(column), new Variant(1)).toDispatch(); // 设置row,column,表格外框宽度Dispatch cols = Dispatch.get(newTable, "Columns").toDispatch(); // 此表的所有列,int colCount = Dispatch.get(cols, "Count").changeType(V ariant.VariantInt).getInt();// 一共有多少列实际上这个数==column System.out.println(colCount + "列");for (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").changeType(V ariant.VariantInt).getInt();// 当前列中单元格数实际上这个数等于rowfor (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 void putTxtToCell(Dispatch table, int cellRowIdx, int cellColIdx,String txt) {Dispatch cell = Dispatch.call(table, "Cell", new Variant(cellRowIdx),new V ariant(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 void 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 V ariant(cellColIdx)).toDispatch();Dispatch.call(cell, "Select");Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch(); // 输入内容需要的对象Dispatch.put(selection, "Text", txt);}// 合并两个单元格public void mergeCell(Dispatch cell1, Dispatch cell2) {Dispatch.call(cell1, "Merge", cell2);}public void mergeCell(Dispatch table, int row1, int col1, int row2, int col2) {Dispatch cell1 = Dispatch.call(table, "Cell", new Variant(row1),new V ariant(col1)).toDispatch();Dispatch cell2 = Dispatch.call(table, "Cell", new Variant(row2),new V ariant(col2)).toDispatch();mergeCell(cell1, cell2);}public void mergeCellTest() {Dispatch tables = Dispatch.get(document, "Tables").toDispatch();int tableCount = Dispatch.get(tables, "Count").changeType(V ariant.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 void moveUp(int pos) {Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch(); // 输入内容需要的对象for (int i = 0; i < pos; i++) {// MoveDown MoveLeft moveRight// moveStart ( Dispatch.call(selection, "HomeKey", new Variant(6));// )// moveEnd Dispatch.call(selection, "EndKey", new Variant(6));Dispatch.call(selection, "MoveUp");}}/** *//*** 从选定内容或插入点开始查找文本** @param toFindText* 要查找的文本* @return boolean true-查找到并选中该文本,false-未查找到文本*/public boolean find(String toFindText) {if (toFindText == null || toFindText.equals(""))return false;Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch(); // 输入内容需要的对象// 从selection所在位置开始查询Dispatch find = Dispatch.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 toFindText* 查找字符串* @param newText* 要替换的内容* @returnpublic boolean replaceText(String toFindText, String newText) {if (!find(toFindText))return false;Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch(); // 输入内容需要的对象Dispatch.put(selection, "Text", newText);return true;}public void printFile() {// Just print the current document to the default printerDispatch.call(document, "PrintOut");}// 保存文档的更改public void save() {Dispatch.call(document, "Save");}public void saveFileAs(String filename) {Dispatch.call(document, "SaveAs", filename);}public void closeDocument() {// Close the document without saving changes// 0 = wdDoNotSaveChanges// -1 = wdSaveChanges// -2 = wdPromptToSaveChangesDispatch.call(document, "Close", new Variant(0));document = null;}public void closeWord() {Dispatch.call(MsWordApp, "Quit");MsWordApp = null;document = null;}// 设置wordApp打开后窗口的位置public void setLocation() {Dispatch activeWindow = Dispatch.get(MsWordApp, "Application").toDispatch();Dispatch.put(activeWindow, "WindowState", new Variant(1)); // 0=default// 1=maximize// 2=minimizeDispatch.put(activeWindow, "Top", new Variant(0));Dispatch.put(activeWindow, "Left", new Variant(0));Dispatch.put(activeWindow, "Height", new Variant(600));Dispatch.put(activeWindow, "width", new Variant(800));}public class JacobTest2 {public static void 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.saveFileAs("d:\\a.doc");// word.closeDocument();// word.closeWord();}public static void openAnExistsFileTest() {WordBean wordBean = new WordBean();wordBean.setVisible(true); // 是否前台打开word 程序,或者后台运行wordBean.openFile("d:\\a.doc");wordBean.insertJpeg("D:" + File.separator + "a.jpg"); // 插入图片(注意刚打开的word// ,光标处于开头,故,图片在最前方插入)wordBean.save();wordBean.closeDocument();wordBean.closeWord();}public static void insertFormatStr(String str) {WordBean wordBean = new WordBean();wordBean.setVisible(true); // 是否前台打开word 程序,或者后台运行wordBean.createNewDocument();// 创建一个新文档wordBean.insertFormatStr(str);// 插入一个段落,对其中的字体进行了设置}public static void insertTableTest() {WordBean wordBean = new WordBean();wordBean.setVisible(true); // 是否前台打开word 程序,或者后台运行wordBean.createNewDocument();// 创建一个新文档wordBean.setLocation();wordBean.insertTable("表名", 3, 2);wordBean.saveFileAs("d:\\table.doc");wordBean.closeDocument();wordBean.closeWord();}public static void mergeTableCellTest() {insertTableTest();//生成d:\\table.docWordBean wordBean = new WordBean();wordBean.setVisible(true); // 是否前台打开word 程序,或者后台运行wordBean.openFile("d:\\table.doc");wordBean.mergeCellTest();}public static void main(String[] args) {// 进行测试前要保证d:\\a.jpg 图片文件存在// createANewFileTest();//创建一个新文件// openAnExistsFileTest();// 打开一个存在的文件// insertFormatStr("格式化字符串");//对字符串进行一定的修饰//insertTableTest();// 创建一个表格mergeTableCellTest();// 对表格中的单元格进行合并}}import java.io.File;import com.jacob.activeX.ActiveXComponent;import .Dispatch;import .Variant;class WordBean {// 代表一个word 程序private ActiveXComponent MsWordApp = null;// 代表进行处理的word 文档private Dispatch document = null;public WordBean() {// Open Word if we\'ve not done it alreadyif (MsWordApp == null) {MsWordApp = new ActiveXComponent("Word.Application");}}// 设置是否在前台打开word 程序,public void setVisible(boolean visible) {MsWordApp.setProperty("Visible", new Variant(visible));// 这一句作用相同// Dispatch.put(MsWordApp, "Visible", new Variant(visible));}// 创建一个新文档public void 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 void 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)/* 是否进行转换ConfirmConversions */,new Variant(false)/* 是否只读*/).toDispatch();// document = Dispatch.invoke(documents, "Open", Dispatch.Method,// new Object[] { wordFilePath, new Variant(true),// new Variant(false)// }, new int[1]).toDispatch();}// 向document 中插入文本内容public void 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, "MoveRight", new Variant(1), new Variant(1));// Put the specified text at the insertion pointDispatch.put(selection, "Text", textToInsert);// 取消选中,应该就是移动光标Dispatch.call(selection, "MoveRight", new Variant(1), new Variant(1));}// 向文档中添加一个图片,public void insertJpeg(String jpegFilePath) {Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch();Dispatch image = Dispatch.get(selection, "InLineShapes").toDispatch();Dispatch.call(image, "AddPicture", jpegFilePath);}// 段落的处理,插入格式化的文本public void 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").changeType(Variant.VariantInt).getInt();// 一共的段落数// 找到刚输入的段落,设置格式Dispatch lastParagraph = Dispatch.call(paragraphs, "Item",new Variant(paragraphCount)).toDispatch(); // 最后一段(也就是刚插入的)// Range 对象表示文档中的一个连续范围,由一个起始字符位置和一个终止字符位置定义Dispatch lastParagraphRange = Dispatch.get(lastParagraph, "Range").toDispatch();Dispatch font = Dispatch.get(lastParagraphRange, "Font").toDispatch();Dispatch.put(font, "Bold", new Variant(true)); // 设置为黑体Dispatch.put(font, "Italic", new Variant(true)); // 设置为斜体Dispatch.put(font, "Name", new Variant("宋体")); //Dispatch.put(font, "Size", new Variant(12)); // 小四Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch();Dispatch.call(selection, "TypeParagraph");// 插入一个空行Dispatch alignment = Dispatch.get(selection, "ParagraphFormat").toDispatch();// 段落格式Dispatch.put(alignment, "Alignment", "2"); // (1:置中2:靠右3:靠左) }// word 中在对表格进行遍历的时候,是先列后行先column 后cell// 另外下标从1开始public void insertTable(String tableTitle, int row, int column) {Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch(); // 输入内容需要的对象Dispatch.call(selection, "TypeText", tableTitle); // 写入标题内容// 标题格行Dispatch.call(selection, "TypeParagraph"); // 空一行段落Dispatch.call(selection, "TypeParagraph"); // 空一行段落Dispatch.call(selection, "MoveDown"); // 游标往下一行// 建立表格Dispatch tables = Dispatch.get(document, "Tables").toDispatch();// int count = Dispatch.get(tables,// "Count").changeType(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").changeType(Variant.VariantInt).getInt();// 一共有多少列实际上这个数==column System.out.println(colCount + "列");for (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").changeType(Variant.VariantInt).getInt();// 当前列中单元格数实际上这个数等于rowfor (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 void 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 void 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 void mergeCell(Dispatch cell1, Dispatch cell2) {Dispatch.call(cell1, "Merge", cell2);}public void 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 void mergeCellTest() {Dispatch tables = Dispatch.get(document, "Tables").toDispatch();int tableCount = Dispatch.get(tables, "Count").changeType(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 void moveUp(int pos) {Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch(); // 输入内容需要的对象for (int i = 0; i < pos; i++) {// MoveDown MoveLeft moveRight// moveStart ( Dispatch.call(selection, "HomeKey", new Variant(6));// )// moveEnd Dispatch.call(selection, "EndKey", new Variant(6));Dispatch.call(selection, "MoveUp");}}/** *//*** 从选定内容或插入点开始查找文本** @param toFindText* 要查找的文本* @return boolean true-查找到并选中该文本,false-未查找到文本*/public boolean find(String toFindText) {if (toFindText == null || toFindText.equals(""))return false;Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch(); // 输入内容需要的对象// 从selection所在位置开始查询Dispatch find = Dispatch.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 toFindText* 查找字符串* @param newText* 要替换的内容* @return*/public boolean replaceText(String toFindText, String newText) {if (!find(toFindText))return false;Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch(); // 输入内容需要的对象Dispatch.put(selection, "Text", newText);return true;}public void printFile() {// Just print the current document to the default printerDispatch.call(document, "PrintOut");}// 保存文档的更改public void save() {Dispatch.call(document, "Save");}public void saveFileAs(String filename) {Dispatch.call(document, "SaveAs", filename);}public void closeDocument() {// Close the document without saving changes// 0 = wdDoNotSaveChanges// -1 = wdSaveChanges// -2 = wdPromptToSaveChangesDispatch.call(document, "Close", new Variant(0));document = null;}public void closeWord() {Dispatch.call(MsWordApp, "Quit");MsWordApp = null;document = null;}// 设置wordApp打开后窗口的位置public void setLocation() {Dispatch activeWindow = Dispatch.get(MsWordApp, "Application").toDispatch();Dispatch.put(activeWindow, "WindowState", new Variant(1)); // 0=default// 1=maximize// 2=minimizeDispatch.put(activeWindow, "Top", new Variant(0));Dispatch.put(activeWindow, "Left", new Variant(0));Dispatch.put(activeWindow, "Height", new Variant(600));Dispatch.put(activeWindow, "width", new Variant(800));}}public class JacobTest2 {public static void 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.saveFileAs("d:\\a.doc");// word.closeDocument();// word.closeWord();}public static void openAnExistsFileTest() {WordBean wordBean = new WordBean();wordBean.setVisible(true); // 是否前台打开word 程序,或者后台运行wordBean.openFile("d:\\a.doc");wordBean.insertJpeg("D:" + File.separator + "a.jpg"); // 插入图片(注意刚打开的word// ,光标处于开头,故,图片在最前方插入)wordBean.save();wordBean.closeDocument();wordBean.closeWord();}public static void insertFormatStr(String str) {WordBean wordBean = new WordBean();wordBean.setVisible(true); // 是否前台打开word 程序,或者后台运行wordBean.createNewDocument();// 创建一个新文档wordBean.insertFormatStr(str);// 插入一个段落,对其中的字体进行了设置}public static void insertTableTest() {WordBean wordBean = new WordBean();wordBean.setVisible(true); // 是否前台打开word 程序,或者后台运行wordBean.createNewDocument();// 创建一个新文档wordBean.setLocation();wordBean.insertTable("表名", 3, 2);wordBean.saveFileAs("d:\\table.doc");wordBean.closeDocument();wordBean.closeWord();}public static void mergeTableCellTest() {insertTableTest();//生成d:\\table.docWordBean wordBean = new WordBean();wordBean.setVisible(true); // 是否前台打开word 程序,或者后台运行wordBean.openFile("d:\\table.doc");wordBean.mergeCellTest();}public static void main(String[] args) {// 进行测试前要保证d:\\a.jpg 图片文件存在// createANewFileTest();//创建一个新文件// openAnExistsFileTest();// 打开一个存在的文件// insertFormatStr("格式化字符串");//对字符串进行一定的修饰//insertTableTest();// 创建一个表格mergeTableCellTest();// 对表格中的单元格进行合并}}出处:/jixiuffff/archive/2010/05/23/5618287.aspx。