jacob,操作word表格

合集下载

基于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常用的方法

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。

Java利用jacob实现文档格式转换

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");*/}}。

【jacobword】使用jacob,合并多个word为一个word文件

【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文档操作技术

基手JACOB韵WORD文档操作技术
J AC0B
式, 这 种 文 档 不 能 通 过 类似 调 用 普 通 的 文
件 操 作 函数 来 进 行 操 作 。 不 少 技 术 人 员在 W ORD文 档 的 控 制 方法 上 进 行 了探 讨 , 文
J a c o b . d l l
献” 中介 绍 了在 VC ++平 台下 使 用 C OM 技 术调 用OLE 自动 化 对 象 , 一 般 是 通 过 加 载 OF F I CE自带 的 对 象 库 创 建 内部 组 件 对 象, 通 过 对 这 些 对 象 的 操 作 实 现 WORD的
Q: 唑
T Tech n ol ogy I nn ov at i o n 4 - 1 er a l d
基手J A C OB 1 6 I 勺 wO R D 文档操作技术①
车晓波 闰旭琴 刘晓建 ( 山东省汽 车电子技术重点实验室 ,山东省科学院 自动化研究所
自动 化 。 文 献 介 绍 了如何 通 过 VC + + 调 用
J NI
VB A将 报 表 内容 输 出到 W ORD应 用 程 序
中。 文 献 介 绍 了在J A V A中运 用 J AC OB  ̄ I 基 干C OM 组 件 的 数 据 源 之 间 的 数 据 结 构 转 换。 诸 多文 献 讲 述 了在 VC++平 台 下 实
在 项 目实 施 中 , 常 常 需 要 将 系 统 运 行 结果 、 工 程 设 计 方 案 或 者 自定 义 内 容 作 为
WORD 文 档 输 出, 以 方便 用 户查 看 。 单 纯 依
C o ej r a c o b . Ac t i v e X.
靠 人 工编 写 项 目报 告、 填 写设 计 内容 不仅 工

jacob操作word

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线程。

用VBA操作word表格Word的表格功能是非常重要的一个功能

用VBA操作word表格Word的表格功能是非常重要的一个功能
下面的代码为所选内容中每张表格的第一行应用底纹。For Each...Next循环用来循环遍历所选内容中的每个表格。
If Selection.Tables.Count >= 1 Then
For Each aTable In Selection.Tables
aTable.Rows(1).Shading.Texture = wdTexture10Percent
If ActiveDocument.Tables.Count >= 1 Then
With ActiveDocument.Tables(1).Cell(Row:=1, Column:=1).Range
.Delete
.InsertAfter Text:="Cell 1,1"
End With
End If
2在表格中插入文字
iCount = 1
For Each oCell In oTable.Range.Cells
oCell.Range.InsertAfter "Cell " & iCount
iCount = iCount + 1
Next oCell
oTable.AutoFormat Format:=wdTableFormatColorful2, ApplyBorders:=True, ApplyFont:=True, _
With MyRange
.Paste
.Collapse Direction:=wdCollapseEnd
.InsertParagraphAfter
.Collapse Direction:=wdCollapseEnd
End With
Next

Java操作word文档使用JACOB和POI操作word,Excel,PPT需要的jar包

Java操作word文档使用JACOB和POI操作word,Excel,PPT需要的jar包

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包引⼊的正确,运⾏编译代码就没有问题.。

jacob操作word(转载)

jacob操作word(转载)

•jacob操作word自从有了JACOB后,事情变得简单多了。

但是要实现Java灵活的控制Word还是一件非常麻烦的事情。

下面介绍几个WORD常见的对象以及一些典型的处理过程,希望对大家有帮助。

(请注意:JDK1.3.2运行 Jacob比较正常,JDK1.4有问题)private ActiveXComponent word = null;private Dispatch documents = null;private Dispatch vSelection = null;private Dispatch wordfile = null;1,初始化word = new ActiveXComponent("Word.Application");documents = word.getProperty("Documents").toDispatch();(将JACOB 放在 WINNT\system32\ 下比较简单省事)2,打开文件wordfile = Dispatch.invoke(documents,"Open",Dispatch.Method,new Object[] {strFileName,new Variant(true),//是否进行转换 ConfirmConversionsnew Variant(false)//是否只读}, new int[1]).toDispatch();vSelection = word.getProperty("Selection").toDispatch();在WORD中,选定内容进行转换时,不用象Java对象一样来回的重新取,这个对象一直有效。

在WORD中3,显示WORDword.setProperty("Visible", new Variant(visible));4,设置WORD的位置Dispatch activeWindow = Dispatch.get(word, "Application").toDispatch();Dispatch.put(activeWindow, "WindowState", new Variant(0));Dispatch.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));进行将JAVA内的数据和WORD交换,常用的做法是,在WORD上作一些特殊的标记,利用 FIND 和 Replace的方法进行,这个方法不是太好。

关于java使用jacob.jar调用word的配置问题

关于java使用jacob.jar调用word的配置问题

关于java使用jacob.jar调用word的配置问题
Java调用jacob出错问题:java.library.path解决
关于java使用jacob.jar调用word的配置问题
最近用到了jacob.jar来转换word文件,出现一些问题都是关于配置的,先将一些配置说明一下,以供大家参考。

一、将jacob.dll拷贝到windows/system32下,并在部署环境中添加jacob.jar包,这两个文件的版本必须一致,不然会出现一些错误,如果多个应用用到改包,最好放到公共包目录下,因为可能出现一些错误。

二、如果通过上述配置还不能正确运用改包,则将jacob.dll放入Java\jdk\jre\bin目录下,如果不是web应用,则需将jacob.dll放到Java\jdk\jre\lib\ext目录下。

如果仍然出现no jacob in the java.library.path错误,把jacob.dll放到System.getProperty("java.library.path")取到的目录下。

(完整版)javajacob操作word文档,进行写操作,如生成表格,添加图片

(完整版)javajacob操作word文档,进行写操作,如生成表格,添加图片

69.
int paragraphCount = Dispatch.get(paragraphs, "Count").changeType(
70.
Variant.VariantInt).getInt();// 一共的段落数
71.
// 找到刚输入的段落,设置格式
72.
Dispatch lastParagraph = Dispatch.call(paragraphs, "Item",
33.
// Find the Documents collection object maintained by Word
34.
// documents 表示 word 的所有文档窗口,(word 是多文档应用程序)
35.
Dispatch documents = Dispatch.get(MsWordApp, "Documents").toDispatch();
36.
document = Dispatch.call(documents, "Open", wordFilePath,
37.
new Variant(true)/* 是否进行转换 ConfirmConversions */,
38.
new Variant(false)/* 是否只读 */).toDispatch();
MsWordApp = new ActiveXComponent("Word.Application");
14.
}
15.
}
16.
// 设置是否在前台打开 word 程序 ,
17.
public void setVisible(boolean visible) {

java通过jacob操作word

java通过jacob操作word

package innet.bysj.word;import java.io.File;import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.Statement;import java.util.ArrayList;import java.util.List;import com.jacob.activeX.ActiveXComponent;import .Dispatch;import .Variant;public class MSWordManager {// word文档private Dispatch doc;// word运行程序对象private ActiveXComponent word;// 所有word文档集合private Dispatch documents;// 选定的范围或插入点private Dispatch selection;private boolean saveOnExit = true;private static final int WORD_HTML = 8;private static final int WORD_TXT = 7;private static final int EXCEL_HTML = 44;/** *//**** @param visible 为true表示word应用程序可见*/public MSWordManager(boolean visible) {if (word == null) {word = new ActiveXComponent("Word.Application");word.setProperty("Visible", new Variant(visible));}if (documents == null)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();}/** *//*** 打开一个已存在的文档** @param docPath*/public void openDocument(String docPath) {closeDocument();doc = Dispatch.call(documents, "Open", docPath).toDispatch();selection = Dispatch.get(word, "Selection").toDispatch();}/** *//*** 把选定的内容或插入点向上移动** @param pos 移动的距离*/public void moveUp(int pos) {if (selection == null)selection = Dispatch.get(word, "Selection").toDispatch();for (int i = 0; i < pos; i++)Dispatch.call(selection, "MoveUp");}/** *//*** 把选定的内容或者插入点向下移动** @param pos 移动的距离*/public void moveDown(int pos) {if (selection == null)selection = Dispatch.get(word, "Selection").toDispatch();for (int i = 0; i < pos; i++)Dispatch.call(selection, "MoveDown");}/** *//*** 把选定的内容或者插入点向左移动** @param pos 移动的距离*/public void moveLeft(int pos) {if (selection == null)selection = Dispatch.get(word, "Selection").toDispatch();for (int i = 0; i < pos; i++) {Dispatch.call(selection, "MoveLeft");}}/** *//*** 把选定的内容或者插入点向右移动** @param pos 移动的距离*/public void moveRight(int pos) {if (selection == null)selection = Dispatch.get(word, "Selection").toDispatch();for (int i = 0; i < pos; i++)Dispatch.call(selection, "MoveRight");}/** *//*** 把插入点移动到文件首位置**/public void moveStart() {if (selection == null)selection = Dispatch.get(word, "Selection").toDispatch();Dispatch.call(selection, "HomeKey", new Variant(6));}public void moveEnd() {if (selection == null)selection = Dispatch.get(word, "Selection").toDispatch();Dispatch.call(selection, "EndKey", new Variant(6));}/** *//*** 从选定内容或插入点开始查找文本** @param toFindText 要查找的文本* @return boolean true-查找到并选中该文本,false-未查找到文本*/public boolean find(String toFindText) {if (toFindText == null || toFindText.equals(""))return false;// 从selection所在位置开始查询Dispatch find = word.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.put(selection, "Text", newText);return true;}/** *//*** 全局替换文本** @param toFindText 查找字符串* @param newText 要替换的内容*/public void replaceAllText(String toFindText, String newText) {while (find(toFindText)) {Dispatch.put(selection, "Text", newText);Dispatch.call(selection, "MoveRight");}}/** *//*** 在当前插入点插入字符串** @param newText 要插入的新字符串*/public void insertText(String newText) {Dispatch.put(selection, "Text", newText);}/** *//**** @param toFindText 要查找的字符串* @param imagePath 图片路径* @return*/public boolean replaceImage(String toFindText, String imagePath) {if (!find(toFindText))return false;Dispatch.call(Dispatch.get(selection, "InLineShapes").toDispatch(), "AddPicture", imagePath);return true;}/** *//*** 全局替换图片** @param toFindText 查找字符串* @param imagePath 图片路径*/public void replaceAllImage(String toFindText, String imagePath) {while (find(toFindText)) {Dispatch.call(Dispatch.get(selection, "InLineShapes").toDispatch(), "AddPicture", imagePath);Dispatch.call(selection, "MoveRight");}}/** *//*** 在当前插入点插入图片** @param imagePath 图片路径*/public void insertImage(String imagePath) {Dispatch.call(Dispatch.get(selection, "InLineShapes").toDispatch(), "AddPicture", imagePath);}/** *//*** 合并单元格** @param tableIndex* @param fstCellRowIdx* @param fstCellColIdx* @param secCellRowIdx* @param secCellColIdx*/public void mergeCell(int tableIndex, int fstCellRowIdx, int fstCellColIdx,int secCellRowIdx, int secCellColIdx) {// 所有表格Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();// 要填充的表格Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex)).toDispatch();Dispatch fstCell = Dispatch.call(table, "Cell",new Variant(fstCellRowIdx), new Variant(fstCellColIdx)).toDispatch();Dispatch secCell = Dispatch.call(table, "Cell",new Variant(secCellRowIdx), new Variant(secCellColIdx)).toDispatch();Dispatch.call(fstCell, "Merge", secCell);}/** *//*** 在指定的单元格里填写数据** @param tableIndex* @param cellRowIdx* @param cellColIdx* @param txt*/public void putTxtToCell(int tableIndex, int cellRowIdx, int cellColIdx,String txt) {// 所有表格Dispatch tables = Dispatch.get(doc, "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.put(selection, "Text", txt);}/** *//*** 在当前文档拷贝数据** @param pos*/public void copy(String toCopyText) {moveStart();if (this.find(toCopyText)) {Dispatch textRange = Dispatch.get(selection, "Range").toDispatch();Dispatch.call(textRange, "Copy");}}/** *//*** 在当前文档粘帖剪贴板数据** @param pos*/public void paste(String pos) {moveStart();if (this.find(pos)) {Dispatch textRange = Dispatch.get(selection, "Range").toDispatch();Dispatch.call(textRange, "Paste");}}/** *//*** 在当前文档指定的位置拷贝表格** @param pos 当前文档指定的位置* @param tableIndex 被拷贝的表格在word文档中所处的位置*/public void copyTable(String pos,int tableIndex) {Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex)).toDispatch();Dispatch range = Dispatch.get(table, "Range").toDispatch();Dispatch.call(range, "Copy");if (this.find(pos)) {Dispatch textRange = Dispatch.get(selection, "Range").toDispatch();Dispatch.call(textRange, "Paste");}}/** *//*** 在当前文档末尾拷贝来自另一个文档中的段落** @param anotherDocPath 另一个文档的磁盘路径* @param tableIndex 被拷贝的段落在另一格文档中的序号(从1开始)*/public void copyParagraphFromAnotherDoc(String anotherDocPath,int paragraphIndex) {Dispatch wordContent = Dispatch.get(doc, "Content").toDispatch(); // 取得当前文档的内容Dispatch.call(wordContent, "InsertAfter", "$selection$");// 插入特殊符定位插入点copyParagraphFromAnotherDoc(anotherDocPath, paragraphIndex, "$selection$");}/** *//*** 在当前文档指定的位置拷贝来自另一个文档中的段落** @param anotherDocPath 另一个文档的磁盘路径* @param tableIndex 被拷贝的段落在另一格文档中的序号(从1开始)* @param pos 当前文档指定的位置*/public void copyParagraphFromAnotherDoc(String anotherDocPath,int paragraphIndex, String pos) {Dispatch doc2 = null;try {doc2 = Dispatch.call(documents, "Open", anotherDocPath).toDispatch();Dispatch paragraphs = Dispatch.get(doc2, "Paragraphs").toDispatch();Dispatch paragraph = Dispatch.call(paragraphs, "Item",new Variant(paragraphIndex)).toDispatch();Dispatch range = Dispatch.get(paragraph, "Range").toDispatch();Dispatch.call(range, "Copy");if (this.find(pos)) {Dispatch textRange = Dispatch.get(selection, "Range").toDispatch();Dispatch.call(textRange, "Paste");}} catch (Exception e) {e.printStackTrace();} finally {if (doc2 != null) {Dispatch.call(doc2, "Close", new Variant(saveOnExit));doc2 = null;}}}/** *//*** 在当前文档指定的位置拷贝来自另一个文档中的表格** @param anotherDocPath 另一个文档的磁盘路径* @param tableIndex 被拷贝的表格在另一格文档中的序号(从1开始)* @param pos 当前文档指定的位置*/public void copyTableFromAnotherDoc(String anotherDocPath, int tableIndex,String pos) {Dispatch doc2 = null;try {doc2 = Dispatch.call(documents, "Open", anotherDocPath).toDispatch();Dispatch tables = Dispatch.get(doc2, "Tables").toDispatch();Dispatch table = Dispatch.call(tables, "Item",new Variant(tableIndex)).toDispatch();Dispatch range = Dispatch.get(table, "Range").toDispatch();Dispatch.call(range, "Copy");if (this.find(pos)) {Dispatch textRange = Dispatch.get(selection, "Range").toDispatch();Dispatch.call(textRange, "Paste");}} catch (Exception e) {e.printStackTrace();} finally {if (doc2 != null) {Dispatch.call(doc2, "Close", new Variant(saveOnExit));doc2 = null;}}}/** *//*** 在当前文档指定的位置拷贝来自另一个文档中的图片** @param anotherDocPath 另一个文档的磁盘路径* @param shapeIndex 被拷贝的图片在另一格文档中的位置* @param pos 当前文档指定的位置*/public void copyImageFromAnotherDoc(String anotherDocPath, int shapeIndex,String pos) {Dispatch doc2 = null;try {doc2 = Dispatch.call(documents, "Open", anotherDocPath).toDispatch();Dispatch shapes = Dispatch.get(doc2, "InLineShapes").toDispatch();Dispatch shape = Dispatch.call(shapes, "Item",new Variant(shapeIndex)).toDispatch();Dispatch imageRange = Dispatch.get(shape, "Range").toDispatch();Dispatch.call(imageRange, "Copy");if (this.find(pos)) {Dispatch textRange = Dispatch.get(selection, "Range").toDispatch();Dispatch.call(textRange, "Paste");}} catch (Exception e) {e.printStackTrace();} finally {if (doc2 != null) {Dispatch.call(doc2, "Close", new Variant(saveOnExit));doc2 = null;}}}/** *//*** 创建表格** @param pos 位置* @param cols 列数* @param rows 行数*/public void createTable(int numCols, int numRows){//(String pos, int numCols, int numRows) {// if (!find(pos)) {Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();Dispatch range = Dispatch.get(selection, "Range").toDispatch();Dispatch newTable = Dispatch.call(tables, "Add", range,new Variant(numRows), new Variant(numCols),new Variant(1)).toDispatch();Dispatch.call(selection, "MoveRight");moveEnd();// }}/** *//*** 在指定行前面增加行** @param tableIndex word文件中的第N张表(从1开始)* @param rowIndex 指定行的序号(从1开始)*/public void addTableRow(int tableIndex, int rowIndex) {// 所有表格Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();// 要填充的表格Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex)).toDispatch();// 表格的所有行Dispatch rows = Dispatch.get(table, "Rows").toDispatch();Dispatch row = Dispatch.call(rows, "Item", new Variant(rowIndex)).toDispatch();Dispatch.call(rows, "Add", new Variant(row));}/** *//*** 在第1行前增加一行** @param tableIndex word文档中的第N张表(从1开始)*/public void addFirstTableRow(int tableIndex) {// 所有表格Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();// 要填充的表格Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex)).toDispatch();// 表格的所有行Dispatch rows = Dispatch.get(table, "Rows").toDispatch();Dispatch row = Dispatch.get(rows, "First").toDispatch();Dispatch.call(rows, "Add", new Variant(row));}/** *//*** 在最后1行前增加一行** @param tableIndex* word文档中的第N张表(从1开始)*/public void addLastTableRow(int tableIndex) {// 所有表格Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();// 要填充的表格Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex)).toDispatch();// 表格的所有行Dispatch rows = Dispatch.get(table, "Rows").toDispatch();Dispatch row = Dispatch.get(rows, "Last").toDispatch();Dispatch.call(rows, "Add", new Variant(row));}/** *//*** 增加一行** @param tableIndex word文档中的第N张表(从1开始)*/public void addRow(int tableIndex) {Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();// 要填充的表格Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex)).toDispatch();// 表格的所有行Dispatch rows = Dispatch.get(table, "Rows").toDispatch();Dispatch.call(rows, "Add");}/** *//*** 增加一列** @param tableIndex word文档中的第N张表(从1开始)*/public void addCol(int tableIndex) {// 所有表格Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();// 要填充的表格Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex)).toDispatch();// 表格的所有行Dispatch cols = Dispatch.get(table, "Columns").toDispatch();Dispatch.call(cols, "Add").toDispatch();Dispatch.call(cols, "AutoFit");}/** *//*** 在指定列前面增加表格的列** @param tableIndex word文档中的第N张表(从1开始)* @param colIndex 指定列的序号(从1开始)*/public void addTableCol(int tableIndex, int colIndex) {// 所有表格Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();// 要填充的表格Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex)).toDispatch();// 表格的所有行Dispatch cols = Dispatch.get(table, "Columns").toDispatch();System.out.println(Dispatch.get(cols, "Count"));Dispatch col = Dispatch.call(cols, "Item", new Variant(colIndex)).toDispatch();// Dispatch col = Dispatch.get(cols, "First").toDispatch();Dispatch.call(cols, "Add", col).toDispatch();Dispatch.call(cols, "AutoFit");}/** *//*** 在第1列前增加一列** @param tableIndex word文档中的第N张表(从1开始)*/public void addFirstTableCol(int tableIndex) {Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();// 要填充的表格Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex)).toDispatch();// 表格的所有行Dispatch cols = Dispatch.get(table, "Columns").toDispatch();Dispatch col = Dispatch.get(cols, "First").toDispatch();Dispatch.call(cols, "Add", col).toDispatch();Dispatch.call(cols, "AutoFit");}/** *//*** 在最后一列前增加一列** @param tableIndex word文档中的第N张表(从1开始)*/public void addLastTableCol(int tableIndex) {Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();// 要填充的表格Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex)).toDispatch();// 表格的所有行Dispatch cols = Dispatch.get(table, "Columns").toDispatch();Dispatch col = Dispatch.get(cols, "Last").toDispatch();Dispatch.call(cols, "Add", col).toDispatch();Dispatch.call(cols, "AutoFit");}/** *//*** 自动调整表格**/public void autoFitTable() {Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();int count = Dispatch.get(tables, "Count").toInt();for (int i = 0; i < count; i++) {Dispatch table = Dispatch.call(tables, "Item", new Variant(i + 1)).toDispatch();Dispatch cols = Dispatch.get(table, "Columns").toDispatch();Dispatch.call(cols, "AutoFit");}}/** *//*** 调用word里的宏以调整表格的宽度,其中宏保存在document下**/public void callWordMacro() {Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();int count = Dispatch.get(tables, "Count").toInt();V ariant vMacroName = new Variant("Normal.NewMacros.tableFit");V ariant vParam = new Variant("param1");V ariant para[] = new Variant[] { vMacroName };for (int i = 0; i < para.length; i++) {Dispatch table = Dispatch.call(tables, "Item", new Variant(i + 1)).toDispatch();Dispatch.call(table, "Select");Dispatch.call(word, "Run", "tableFitContent");}}/** *//*** 设置当前选定内容的字体** @param boldSize* @param italicSize* @param underLineSize 下划线* @param colorSize 字体颜色* @param size 字体大小* @param name 字体名称*/public void setFont(boolean bold, boolean italic, boolean underLine,String colorSize, String size, String name) {Dispatch font = Dispatch.get(selection, "Font").toDispatch();Dispatch.put(font, "Name", new Variant(name));。

如何利用Java-JACOB操作WORD文档

如何利用Java-JACOB操作WORD文档

如何利用Java-JACOB操作WORD文档作者:Hu Baoshun信箱:neu.hubs@JACOB是一个JAVA到微软的COM接口的桥梁。

使用JACOB允许任何JVM访问COM对象,从而使JAVA应用程序能够调用COM对象。

如果你要对MS Word、Excel 进行处理,JACOB 是一个好的选择。

JACOB目前已经成为sourceforge (/projects/jacob-project/)的一个开源项目,本文使用的版本是1.10.1。

因为在项目中用到了这个技术,但是在网上没有查到很符合题目的文章,经过我自己的探索,总结写出了这篇文章。

这篇文章可能不能完全满足你的要求,你也可以按照我的探索方法进行探索:参阅VBA 操作Office的组件的书籍,然后参考下面的Tip完成需要的功能。

文章最后附完整的测试代码。

生成WORD文档的简单讲解:1.初始化com的线程,非常重要,否则第二次创建com对象的时候会出现can’tco-create object异常(参见jacob的帮助文档),完成操作com组件后要调用realease方法ComThread.InitSTA();// 初始化com的线程,非常重要!!使用结束后要调用realease 方法2.初始化word应用程序,新建一个空白文档,取得文档内容对象//Instantiate objWord //Declare word objectActiveXComponent objWord = new ActiveXComponent("Word.Application");//Assign a local word objectDispatch wordObject = (Dispatch) objWord.getObject();//Create a Dispatch Parameter to show the document that is opened Dispatch.put((Dispatch) wordObject, "Visible", new Variant(true));// new Variant(true)表示word应用程序可见Tip:设置一个对象的属性的时候,利用Dispatch的put方法,给属性赋值。

jacob给word加印的功能

jacob给word加印的功能

jacob给word加印的功能花了两天时间,参考了一些资料,总算是处理好了这样一个技术点。

关键的心得如下:使用jacob,重点不是jacob本身,而是office的一些API资料。

比如需要知道光标的移动,包括上下左右的move(MoveUp, MoveDown,MoveLeft, MoveRight),包括回到首页起点Dispatch.put(selection, "Start", 0)等等。

严格的说,这边并没有很系统化的去了解jacob的底层。

但对于一些关键点,还是可以拿出来分享的。

比如插入一张图片之后,系统可以拿到一个Dispatch对象(例如叫做obj),我们则需要调用Dispatch.call(obj,"select"),这样相当于使用鼠标在word选中了新插入的图片,而后我们就可以通过Dispatch得到图片的ShapeRange,进而得到ShapeRange的WrapFormat,再对WrapFormat进行设定。

对应的结构可以归纳为:Image->ShapeRange->WrapFormat。

但是要想知道WrapFormat对应到的是哪些值,且有哪些作用,则需要去查询MSDN。

这边查询到的相关值如下:wdWrapInline 7 将形状嵌入到文字中。

wdWrapNone 3 将形状放在文字前面。

请参阅 wdWrapFront 。

wdWrapSquare 0 使文字环绕形状。

行在形状的另一侧延续。

wdWrapThrough 2 使文字环绕形状。

wdWrapTight 1 使文字紧密地环绕形状。

wdWrapTopBottom 4 将文字放在形状的上方和下方。

wdWrapBehind 5 将形状放在文字后面。

wdWrapFront 6 将形状放在文字前面。

这种匈牙利命名法的变量名,其实都对应到一个整型数据(应该是一个常量型的变量)。

比如这次代码中需要用到的将印章图片盖在文字的前面,对应到得变量是wdWrapFront,也就是数值6.再有就是要知道传入的word文件共有几页,加印的话,应该是每一页都要盖章的,于是就需要通过Dispatch.call(cursor,"information",4)来获取,此时cursor(光标)可能是需要回到word首页的开始位置(还未测试)。

Jacob操作office文档(Word,PPT,Excel)

Jacob操作office文档(Word,PPT,Excel)
98.* @param newName
99.*/
100.privatevoidmodifyCurrentSheetName(String newName) {
101.Dispatch.put(getCurrentSheet(),"name", newName);
102.}
103.
104./**
105.*得到当前工作表的名字
141.privateintgetSheetCount() {
142.intcount = Dispatch.get(getSheets(),"count").toInt();
52.Dispatch.call(workbook,"SaveAs",filePath);
53.}
54./**
55.*关闭excel文档
56.* @param f含义不明(关闭是否保存?默认false)
57.*/
58.privatevoidCloseExcel(booleanf) {
59.try{
60.Dispatch.call(workbook,"Save");
126.returnsheets;
127.}
128./**
129.*通过工作表索引得到工作表(第一个工作簿index为1)
130.* @param index
131.* @return sheet对象
132.*/
133.privateDispatch getSheetByIndex(Integer index) {
16.privateDispatch workbook =null;//具体工作簿
17.privateDispatch sheets =null;//获得sheets集合对象

jacob操作word excel

jacob操作word excel

jacob操作word excel项目开发过程中,需求涉及到了各种文档转换为HTML或者网页易显示格式,现在将实现方式整理如下:一、了解Jacob先了解一下概念,JACOB 就是 JAVA-COM Bridge的缩写,提供自动化的访问com 的功能,也是通过JNI功能访问windows平台下的com组件或者win32系统库的。

这是一个开始于1999年的开源项目的成果,有很多使用者对该项目进行了修改,做出了自己的贡献。

下载地址:/project/showfiles.php?group_id=109543&package_ id=118368二、Jacob安装1、我们解开下载的jacob_1.9.zip,在文件夹中找到jacob.dll和jacob.jar两个文件2、将压缩包解压后,Jacob.jar添加到Libraries中;3、将Jacob.dll放至“WINDOWS\SYSTEM32”下面。

需要注意的是:【使用IDE启动Web服务器时,系统读取不到Jacob.dll,例如用MyEclipse启动Tomcat,就需要将dll文件copy到MyEclipse安装目录的“jre\bin”下面。

一般系统没有加载到Jacob.dll文件时,报错信息为:“ng.UnsatisfiedLinkError: no jacob in java.library.path”】三、使用Jacob转换Word,Excel为HTMLJAVA代码:Java代码1.import java.io.BufferedReader;2.import java.io.BufferedWriter;3.import java.io.File;4.import java.io.FileInputStream;5.import java.io.FileNotFoundException;6.import java.io.FileWriter;7.import java.io.IOException;8.import java.io.InputStreamReader;9.10.import com.jacob.activeX.ActiveXComponent;11.import .Dispatch;12.import .Variant;13.14.public class TransformFiletoHtml15.{16. int WORD_HTML = 8;17. int WORD_TXT = 7;18. int EXCEL_HTML = 44;19.20. /**21. * WORD转HTML22. * @param docfile WORD文件全路径23. * @param htmlfile 转换后HTML存放路径24. */25. public void wordToHtml(String docfile, String htmlfile)26. {27. ActiveXComponent app = new ActiveXComponent("Word.Application"); // 启动word28. try29. {30. app.setProperty("Visible", new Variant(false));31. Dispatch docs = app.getProperty("Documents").toDispatch();32. Dispatch doc = Dispatch.invoke(docs,"Open",Dispatch.Method,new Object[] { docfile, new Variant(false),new Variant( true) }, new int[1]).toDispatch();33. Dispatch.invoke(doc, "SaveAs", Dispatch.Method, newObject[] {htmlfile, new Variant(WORD_HTML) }, new int[1]);34. Variant f = new Variant(false);35. Dispatch.call(doc, "Close", f);36. }37. catch (Exception e)38. {39. e.printStackTrace();40. }41. finally42. {43. app.invoke("Quit", new Variant[] {});44. }45. }46.47. /**48. * EXCEL转HTML49. * @param xlsfile EXCEL文件全路径50. * @param htmlfile 转换后HTML存放路径51. */52. public void excelToHtml(String xlsfile, String htmlfile)53. {54. ActiveXComponent app = new ActiveXComponent("Excel.Application"); // 启动excel55. try56. {57. app.setProperty("Visible", new Variant(false));58. Dispatch excels = app.getProperty("Workbooks").toDispatch();59. Dispatch excel = Dispatch.invoke(excels,"Open",Dispatch.Method,new Object[] { xlsfile, new Variant(false),new Vari ant(true) }, new int[1]).toDispatch();60. Dispatch.invoke(excel, "SaveAs", Dispatch.Method, new Object[] {htmlfile, new Variant(EXCEL_HTML) }, new int[1]);61. Variant f = new Variant(false);62. Dispatch.call(excel, "Close", f);63. }64. catch (Exception e)65. {66. e.printStackTrace();67. }68. finally69. {70. app.invoke("Quit", new Variant[] {});71. }72. }73.74. /**75. * /删除指定文件夹76. * @param folderPath 文件夹全路径77. * @param htmlfile 转换后HTML存放路径78. */79. public void delFolder(String folderPath)80. {81. try82. {83. delAllFile(folderPath); //删除完里面所有内容84. String filePath = folderPath;85. filePath = filePath.toString();86. java.io.File myFilePath = new java.io.File(filePath);87. myFilePath.delete(); //删除空文件夹88. } catch (Exception e) {e.printStackTrace();}89. }90.91. /**92. * /删除指定文件夹下所有文件93. * @param path 文件全路径94. */95. public boolean delAllFile(String path)96. {97. boolean flag = false;98. File file = new File(path);99. if (!file.exists())100. {101. return flag;102. }103. if (!file.isDirectory())104. {105. return flag;106. }107. String[] tempList = file.list();108. File temp = null;109. for (int i = 0; i < tempList.length; i++) 110. {111. if (path.endsWith(File.separator)) 112. {113. temp = new File(path + tempList[i]); 114. }115. else116. {117. temp = new File(path + File.separator + tempList[i]);118. }119. if (temp.isFile())120. {121. temp.delete();122. }123. if (temp.isDirectory())124. {125. delAllFile(path + "/" + tempList[i]);//先删除文件夹里面的文件126. delFolder(path + "/" + tempList[i]);//再删除空文件夹127. flag = true;128. }129. }130. return flag;131. }132.}调用JAVA代码:Java代码1.public class Test1 {2. public static void main(String[] args) {3. // TODO Auto-generated method stub4. TransformFiletoHtml trans = new TransformFiletoHtml();5. trans.wordToHtml("D:\\sinye.doc", "D:\\sinye.html");6. }7.8.}只写了一个测试word转html的,excel转html的同理,在TransformFiletoHtml 类中,写了两个方法,一个是删除文件夹的方法(delFolder()),一个是删除文件夹下所有文件的方法(delAllFile())。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

竭诚为您提供优质文档/双击可除jacob,操作word表格篇一:jacob读取word表格packagetest;importjava.io.bufferedReader;importjava.io.FileReader;importjava.io.ioexception;importjava.util.arraylist;importjava.util.list;importbean.dx;importcom.jacob.activex.activexcomponent;thread;.dispatch;.Variant;publicclassReadwordbystream{ publicstaticvoidmain(string[]args)throwsioexception{dispatchworddoc=null;activexcomponentword=null;try{word=newactivexcomponent("word.application");word.setproperty("Visible",newVariant(false));dispatchdocuments=word.getproperty("documents").tod ispatch();worddoc=dispatch.call(documents,"open","d:\\word\\1 .doc").todispatch();dispatchtables=dispatch.get(worddoc,"tables").todis patch();dispatchtable=dispatch.call(tables,"item",newVarian t(1)).todispatch();dispatchrows=dispatch.get(table, "Rows").todispatch();dispatchcolumns=dispatch.get(table,"columns").todis patch();dispatchcell;dispatchrange;stringdata;//dxd=newdx();//listlist=newarraylist();system.out.println("一共打多少收按行="+dispatch.get(rows,"count").getint());system.out.println("一共多少列="+dispatch.get(columns,"count").getint());for(inti =1;i for(intj=1;jrange=dispatch.get(cell,"Range").todispatch();data=dispatch.get(range,"text").getstring();system.out.print(data.trim()+"|");}system.out.print ln();}}catch(exceptione){e.printstacktrace();}final ly{dispatch.call(worddoc,"close",newVariant(true)); word.invoke("quit",newVariant[0]);}}}篇二:jacob操作word详细教程jacob操作word详细教程博客分类:javatomcatqq应用服务器F#首先,大家先要了解一下jacob,官方的解释是javacombridge,即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/jaco b_1.9.zipmodtime=11094370022.3.importjava.io.bufferedinputstream;4.importjava.io.bufferedoutputstream;5.importjava.io.File;6.importjava.io.Fileinputstream;7.importjava.io.Fileoutputstream;8.importjava.io.inputstream;9.importjava.io.outputstream;10.importjava.text.simpledateFormat;11.importjava.util.arraylist;12.importjava.util.date;13.importjava.util.hashmap;14.importjava.util.iterator;15.importjava.util.list;16.importjava.util.map;17.importjava.util.set;18.19.publicclasswordwriter{20.21.privatewordoperatorword;22.23.publicwordwriter(stringfilepath){24.word=newwordoperator();25.word.opendocument(filepath);26.}27.28.publicwordwriter(inputstreaminput,stringfilepath ,stringfilename)throwsexception{29.stringpath=saveasdocFile(input,filepath,filename );30.word=newwordoperator();31.word.opendocument(path);32.}33./**34.*将word文档输入流保存为本地得到word文件35.*@paraminput36.*@paramfilepath37.*@paramfilename38.*@throwsexception39.*/40.@suppresswarnings("unused")41.privatestringsaveasdocFile(inputstreaminput,stri ngfilepath,stringfilename)throwsexception{42.if(!stringutils.isValidatestring(filepath)||!str ingutils.isValidatestring(filename)){43.thrownewexception("thefilepathorfilenameiserror" );44.}45.if(input==null){46.thrownewexception("inputstreamisnull");47.}48.Filefile=newFile(filepath);49.50.if(!file.exists()){51.thrownewexception("theFilepathisnull");52.}53.filepath=validateFilepath(filepath);54.filename=getRandomFilename(filename);55.inputstreamin=null;56.outputstreamout=null;57.try{58.in=newbufferedinputstream(input);59.out=newbufferedoutputstream(newFileoutputstream(filepath+filename));60.byte[]b=newbyte[1024];61.for(intp=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.returnfilepath+filename;74.}75./**76.*验证word文件路径77.*@paramfilepath78.*@return79.*/80.privatestringvalidateFilepath(stringfilepath){81.if((stindexof("\\\\")==-1)83.}84.returnfilepath;85.}86./**87.*生成一个新的文件名(保证文件名不相同)88.*@paramfilename89.*@return90.*/91.privatestringgetRandomFilename(stringfilename){92.filename=filename+"_"+newsimpledateFormat("yyyym mddhhmmssz").format(newdate())+".doc";93.returnfilename;94.}95./**96.*replacetext97.*@parammap98.*/99.publicvoidreplacealltext(mapmap){100.if(map==nul l){101.return;102.}103.setkeys=map.keyset();104.iteratorit=keys.iterator();105.while(it.hasnext()){106.stringkey=it.next();107.word.replacealltext(key,map.get(key));108.} 109.}110./**111.*adddetails112.*@paramvalues113.*/114.publicvoidinsertcontextinRow(list>values,inttab leindex){115.if(tableindex 116.tableindex=1;117.}118.if(values==null||values.size()119.return;120.}122.mapm=values.get(0);123.setkeys=m.keyset();124.iteratorit=keys.iterator();125.while(it.hasnext()){126.stringstr=it.next();127.128.int[]a=word.gettablecellpostion(str,tableindex);129.if(a!=null131.}132.133.}134.if(p!=nulli136.word.addtableRow(tableindex,p[0]);//在表格插入行数137.}138.}139.140.iteratorit2=keys.iterator();141.while(it2.hasnext()){143.intcol=0;144.stringstr=it2.next();145.146.int[]a=word.gettablecellpostion(str,tableindex);147.if(a!=null){148.col=a[1];149.}150.for(mapmap:values){151.word.puttxttocell(tableindex,row,col,map.get(st r));152.row++;153.}154.}155.156.}157.158./**159.*closedocument160.*/。

相关文档
最新文档