jacob操作word excel
基于JACOB的WORD文档操作技术
为例,详细讲解了JACOB技术的使用方法。分析了如何利用COM技术控制WORD对象进行文档编辑,对OFFICE产品的自动化操作以及在JAVA平
台下操纵本地COM组件都有参考意义。
关键词:JACOB WORD操作 COM组件
中图分类号:TP311.52
文献标识码:A
文章编号:1674-098X(2013)02(a)-0029-02
IT技术
科技创新导报 2013 NO.04
Science and Technology Innovation Herald
基于JACOB的WORD文档操作技术①
车晓波 闫旭琴 刘晓建 (山东省汽车电子技术重点实验室,山东省科学院自动化研究所 山东济南 250014)
摘 要:该文在介绍COM自动化组件、VBA宏技术的基础上,阐述了JACOB的原理以及与两者之间的关系,在JAVA程序中以JACOB调用COM组件
1 JACOB介绍 JACOB 是JAVA-COM Br idge的缩
写,它在JAVA与微软的COM 组件之间构建 一座桥梁。由于JAVA 程 序不能 直接调用本 地COM自动化组件,解 决JAVA对本地操作 的一种方法就是JNI。JNI是JAVA Nat ive I nt e r f a c e 的缩写,中文为JAVA 本地调用。从 JAVA 1.1开始,JNI标准就成为JAVA平台 的一部分,它允许JAVA代码和其他语言写的 代 码 进行交 互。JAC O B 的实质也 是 通 过 J N I 实 现 的,在 JAC O B中包含了一 个 C+ +程 序 编 译的JACOB.d l l库文件,在该库文件中实现 了与本地COM组件的通讯,然后JACOB通过 J N I访问动态 库的 方 式实 现了在JAVA平台上
基于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读取word表格
package test;import java.io.BufferedReader;import java.io.FileReader;import java.io.IOException;import java.util.ArrayList;import java.util.List;import bean.DX;import com.jacob.activeX.ActiveXComponent;import Thread;import .Dispatch;import .Variant;public class ReadWordByStream {public static void main(String[] args) throws IOException {Dispatch wordDoc = null;ActiveXComponent word = null;try {word = new ActiveXComponent("Word.Application");word.setProperty("Visible", new Variant(false));Dispatch documents = word.getProperty("Documents").toDispatch();wordDoc = Dispatch.call(documents, "Open", "d:\\word\\1.doc").toDispatch();Dispatch tables = Dispatch.get(wordDoc, "Tables").toDispatch();Dispatch table = Dispatch.call(tables, "Item", new Variant(1)).toDispatch();Dispatch rows = Dispatch.get(table, "Rows").toDispatch();Dispatch columns = Dispatch.get(table, "Columns").toDispatch();Dispatch cell;Dispatch range;String data;//DX d=new DX();//List<DX> list=new ArrayList<DX>();System.out.println("一共打多少收按行="+Dispatch.get(rows, "Count").getInt());System.out.println("一共多少列="+Dispatch.get(columns, "Count").getInt());for (int i = 1; i <= Dispatch.get(rows, "Count").getInt(); i++) {for (int j = 1; j <= Dispatch.get(columns, "Count").getInt(); j++) {cell = Dispatch.call(table, "Cell", i, j).toDispatch();range = Dispatch.get(cell, "Range").toDispatch();data = Dispatch.get(range, "Text").getString();System.out.print(data.trim() + "|");}System.out.println();}} catch (Exception e) {e.printStackTrace();} finally {Dispatch.call(wordDoc, "Close", new Variant(true));word.invoke("Quit", new Variant[0]);}}}。
【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。
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
最近由于工作的原因需要对Word进行操作,并且在文档上面加上水印,这个问题我在网上搜索了很久都没有一个完整的解决办法,没得办法之好自己研究了,半天的努力没有白费,终于解决了,有兴趣的朋友可以参考下:环境:jdk1.4jacob 1.9office2003至于jacob的设置我就不用多说了,网上很多这样的文章,下面就把我的代码贴出来,供大家参考。
package src;import com.jacob.activeX.ActiveXComponent;import .Dispatch;import .Variant;import Thread;public class WordObj{public WordObj(){}private static WordObj instance;private Dispatch doc = null;private Dispatch activeWindow = null;private Dispatch docSelection = null;private Dispatch wrdDocs = null;private String fileName;private ActiveXComponent wrdCom;/*** 获取Word操作静态实例对象** @return 报表汇总业务操作*/public final static synchronized WordObj getInstance()if (instance == null)instance = new WordObj();return instance;}/*** 初始化Word对象** @return 是否初始化成功*/public boolean initWordObj(){boolean retFlag = false;ComThread.InitSTA();// 初始化com的线程,非常重要!!使用结束后要调用 realease方法wrdCom = new ActiveXComponent("Word.Application");try{// 返回wrdCom.Documents的DispatchwrdDocs = wrdCom.getProperty("Documents").toDispatch();wrdCom.setProperty("Visible", new Variant(true));retFlag = true;}catch (Exception e){retFlag = false;e.printStackTrace();}return retFlag;}/*** 创建一个新的word文档**/public void createNewDocument(){doc = Dispatch.call(wrdDocs, "Add").toDispatch();docSelection = Dispatch.get(wrdCom, "Selection").toDispatch(); }* 取得活动窗体对象**/public void getActiveWindow(){// 取得活动窗体对象activeWindow = wrdCom.getProperty("ActiveWindow").toDispatch();}/*** 打开一个已存在的文档** @param docPath*/public void openDocument(String docPath){if (this.doc != null){this.closeDocument();}doc = Dispatch.call(wrdDocs, "Open", docPath).toDispatch();docSelection = Dispatch.get(wrdCom, "Selection").toDispatch(); }/*** 关闭当前word文档**/public void closeDocument(){if (doc != null){Dispatch.call(doc, "Save");Dispatch.call(doc, "Close", new Variant(0));doc = null;}}/*** 文档设置水印** @param waterMarkStr 水印字符串public void setWaterMark(String waterMarkStr){// 取得活动窗格对象Dispatch activePan = Dispatch.get(activeWindow, "ActivePane").toDispatch();// 取得视窗对象Dispatch view = Dispatch.get(activePan, "View").toDispatch();//输入页眉内容Dispatch.put(view, "SeekView", new Variant(9));Dispatch headfooter = Dispatch.get(docSelection, "HeaderFooter") .toDispatch();//取得图形对象Dispatch shapes = Dispatch.get(headfooter, "Shapes").toDispatch(); //给文档全部加上水印Dispatch selection = Dispatch.call(shapes, "AddTextEffect",new Variant(9), waterMarkStr, "宋体", new Variant(1),new Variant(false), new Variant(false), new Variant(0),new Variant(0)).toDispatch();Dispatch.call(selection, "Select");//设置水印参数Dispatch shapeRange = Dispatch.get(docSelection, "ShapeRange") .toDispatch();Dispatch.put(shapeRange, "Name", "PowerPlusWaterMarkObject1"); Dispatch textEffect =Dispatch.get(shapeRange,"TextEffect").toDispatch();Dispatch.put(textEffect, "NormalizedHeight", new Boolean(false)); Dispatch line = Dispatch.get(shapeRange, "Line").toDispatch(); Dispatch.put(line, "Visible", new Boolean(false));Dispatch fill = Dispatch.get(shapeRange, "Fill").toDispatch(); Dispatch.put(fill, "Visible", new Boolean(true));//设置水印透明度Dispatch.put(fill, "Transparency", new Variant(0.5));Dispatch foreColor =Dispatch.get(fill,"ForeColor").toDispatch();//设置水印颜色Dispatch.put(foreColor, "RGB", new Variant(16711680));Dispatch.call(fill, "Solid");//设置水印旋转Dispatch.put(shapeRange, "Rotation", new Variant(315));Dispatch.put(shapeRange, "LockAspectRatio", new Boolean(true)); Dispatch.put(shapeRange, "Height", new Variant(117.0709));Dispatch.put(shapeRange, "Width", new Variant(468.2835));Dispatch.put(shapeRange, "Left", new Variant(-999995));Dispatch.put(shapeRange, "Top", new Variant(-999995));Dispatch wrapFormat = Dispatch.get(shapeRange, "WrapFormat").toDispatch();//是否允许交叠Dispatch.put(wrapFormat, "AllowOverlap", new Variant(true)); Dispatch.put(wrapFormat, "Side", new Variant(3));Dispatch.put(wrapFormat, "Type", new Variant(3));Dispatch.put(shapeRange, "RelativeHorizontalPosition", new Variant(0));Dispatch.put(shapeRange, "RelativeVerticalPosition", new Variant(0));Dispatch.put(view, "SeekView", new Variant(0));}/*** 关闭Word资源***/public void closeWordObj(){// 关闭word文件wrdCom.invoke("Quit", new Variant[] {});// 释放com线程。
使用Jacob向Excel中插入图片
使用Jacob向Excel中插入图片2008-12-15 18:30详细的部署步骤:1、因为本人使用的JDK1.4,所以需要下载Jacob1.11.1版本2、解压该Jacob,导入其jar文件到IDE的lib下,3、拷贝jacob中的x86的dll文件到你使用的JDK的bin目录下import java.io.File;import java.io.FileInputStream;import java.util.ArrayList;import java.util.Properties;import java.util.StringTokenizer;import com.jacob.activeX.ActiveXComponent;import Thread;import .Dispatch;import .Variant;/*** 使用JACOB插件,在不改變模板中任何內容的情況下,向Excel中插入圖片和日期* @author owen.bear* @version v1.0* @date 2008-12-15*/public class SuccessfullyInsertValue {private static ActiveXComponent excel;private static Dispatch workbooks = null;private static Dispatch workbook = null;private static Dispatch sheets = null;private static Dispatch sheet = null;public static void main(String[] args) {SuccessfullyInsertValue insert = new SuccessfullyInsertValue(); String excelFilePath = "C:\\TestExcel\\target\\Test.xls";String sheetName = "FileDetails";String picFilePath = "C:\\TestExcel\\pic\\a.jpg";String proName = "columns";String proFilePath = "C:\\TestExcel\\conf\\columns.properties"; String queryCode = "123456";String signDate = "2008-12-15";insert.OpenExcel(excelFilePath);insert.insertPicture2Excel(excelFilePath, sheetName, picFilePath, proName, proFilePath, queryCode, signDate);insert.CloseExcel();}/*** 向Excel中插入图片和日期* @param excelFilePath 需要插入图片和日期的Excel路径* @param sheetName 当前需要插入图片和日期的Excel表* @param picFilePath 插入图片的路径* @param proName 列列表* @param proFilePath 配置文件路径* @param queryCode 定位的查询依据* @param signDate 当前需要插入的日期*/public void insertPicture2Excel(String excelFilePath, String sheetName, String picFilePath, String proName, String proFilePath, String queryCode, String signDate) {sheets = Dispatch.call(workbook, "Worksheets").toDispatch();sheet = Dispatch.call(sheets, "Item", sheetName).toDispatch();Dispatch.call(sheet, "Select"); //定位需要插入图片的工作表ArrayList list = getColunmsByProperties(proName, proFilePath);int position = getPosition(list, queryCode, excelFilePath, sheetName);String picPosition = "F" + (position -2);String datePosition = "F" + (position -1);//插入图片Dispatch d = Dispatch.invoke(sheet, "Range", Dispatch.Get, new Object[]{ picPosition }, new int[1]).toDispatch();Dispatch.call(d, "Select"); //在工作表中,定位需要插入图片的具体位置Dispatch select = Dispatch.call(sheet, "Pictures").toDispatch(); Dispatch pic=Dispatch.call(select, "Insert",picFilePath).toDispatch();Dispatch.put(pic, "Height", "25"); //图片在Excel中显示的高Dispatch.put(pic, "Width", "75"); //图片在Excel中显示的宽//插入日期Dispatch cell = Dispatch.invoke(sheet, "Range", Dispatch.Get, new Object[] { datePosition }, new int[1]).toDispatch();Dispatch.put(cell, "Value", signDate);Dispatch.call(workbook, "Close", new Variant(true)); //将开启的Excel表保存后关闭}/*** 通过定位查询依据,获取插入图片和时间的行* @param list 列列表的集合* @param queryCode* @param excelFilePath* @param sheetName* @return 插入图片和时间的具体行*/public int getPosition(ArrayList list, String queryCode, String excelFilePath, String sheetName) {int position = 0;boolean flag = true;int m = 1;while(flag) {for(int i = 0; i < list.size(); i++){String columnX = (String)list.get(i);Dispatch cell = Dispatch.invoke(sheet, "Range", Dispatch.Get, new Object[] { columnX + m }, new int[1]).toDispatch();String columnValue = Dispatch.get(cell, "Value").toString();if(columnValue.startsWith(queryCode)){position = m;flag = false;break;}}m++;}System.out.println("position = " + position);return position;}/*** 读取配置文件,获取列列表的集合* @param proName* @param proFilePath* @return 列列表的集合*/public ArrayList getColunmsByProperties(String proName, StringproFilePath){ArrayList list = new ArrayList();try{Properties properties = new Properties();FileInputStream fin = new FileInputStream(new File(proFilePath)); properties.load(fin);String allColunms = properties.getProperty(proName);System.out.println("allColunms = " + allColunms);if(allColunms != null) {StringTokenizer st = new StringTokenizer(allColunms, ",");while(st != null && st.hasMoreElements()) {String temp = (String)st.nextElement();list.add(temp);}}}catch(Exception e){e.printStackTrace();}return list;}/*** 关闭Excel文档* @param file*/private static void OpenExcel(String file) {try {ComThread.InitSTA();excel = new ActiveXComponent("Excel.Application");excel.setProperty("Visible", new Variant(false));workbooks = excel.getProperty("Workbooks").toDispatch();workbook = Dispatch.invoke(workbooks, "Open", Dispatch.Method, new Object[] { file, new Variant(false), new Variant(false) }, newint[1]).toDispatch();} catch (Exception e) {e.printStackTrace();}}/*** 退出Excel,并关闭进程*/private static void CloseExcel() {excel.invoke("Quit", new Variant[] {});ComThread.Release(); //关闭进程}}配置文件内容如下:columns=A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,AA,AB,AC, AD,AE,AF,AG,AH。
jacob,操作word表格
竭诚为您提供优质文档/双击可除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。
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的方法进行,这个方法不是太好。
jacob 操作说明
}
public void openDocument(String docPath, String pwd)throws Exception {
for (int i = 0; i < pos; i++)
Dispatch.call(selection, "MoveUp");
}
/**
* 把选定的内容或者插入点向下移动
*
* @param pos
word.setProperty("Visible", new Variant(false)); //不可见打开word
word.setProperty("AutomationSecurity", new Variant(3)); //禁用宏
}
if (documents == null)
documents = word.getProperty("Documents").toDispatch();
}
/**
* 设置退出时参数
*/
@SuppressWarnings("static-access")
public boolean find(String toFindText) {
if (toFindText == null || toFindText.equals(""))
selection = Dispatch.get(word, "Selection").toDispatch();
关于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文档,进行写操作,如生成表格,添加图片
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
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如何操作Word, Excel, PDF文档
{
Dispatch.call(document,"SaveAs",filename);
}
public void printFile()
WordBean word=new WordBean();
word.openWord(true);
word.createNewDocument();
word.insertText("Hello word.");
}
}
import com.jacob.activeX.*;
1、一个jacob操作Word的例子,其他操作excel,pdf的sample里都有
import java.io.File;
import .*;
import com.jacob.activeX.*;
public class WordTest {
public static void main(String[] args) {
//Call the Add method of the Documents collection to create
//a new document to edit
document = Dispatch.call(documents,"Add").toDispatch();
}
// the top of the new doc
Dispatch selection =
Dispatch.get(MsWordApp,"Selection").toDispatch();
Jacob操作office文档(Word,PPT,Excel)
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项目开发过程中,需求涉及到了各种文档转换为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())。
【转】Jacob操作Excel
【转】Jacob操作Excelimport com.jacob.activeX.ActiveXComponent;import Thread;import .Dispatch;import .Variant;public class JacobExcelTool {private static ActiveXComponent xl = null; //Excel对象(防止打开多个)private static Dispatch workbooks = null; //工作簿对象private Dispatch workbook = null; //具体工作簿private Dispatch sheets = null;// 获得sheets集合对象private Dispatch currentSheet = null;// 当前sheetpublic ActiveXComponent getXl() {return xl;}public Dispatch getWorkbooks() {return workbooks;}public Dispatch getWorkbook() {return workbook;}/*** 打开excel文件* @param filepath 文件路径名称* @param visible 是否显示打开* @param readonly 是否只读方式打开*/public void OpenExcel(String filepath, boolean visible, boolean readonly) {try {initComponents(); //清空原始变量ComThread.InitSTA();if(xl==null)xl = new ActiveXComponent("Excel.Application"); //Excel对象xl.setProperty("Visible", new Variant(visible));//设置是否显示打开excelif(workbooks==null)workbooks = xl.getProperty("Workbooks").toDispatch(); //工作簿对象workbook = Dispatch.invoke( //打开具体工作簿workbooks,"Open",Dispatch.Method,new Object[] { filepath, new Variant(false),new Variant(readonly) },// 是否以只读方式打开new int[1]).toDispatch();} catch (Exception e) {e.printStackTrace();releaseSource();}}/*** 工作簿另存为* @param filePath 另存为的路径*/public void SaveAs(String filePath){Dispatch.invoke(workbook, "SaveAs", Dispatch.Method, new Object[] { filePath,new Variant(44) }, new int[1]);}/*** 关闭excel文档* @param f 含义不明(关闭是否保存?默认false)*/public void CloseExcel(boolean f,boolean quitXl) {try {Dispatch.call(workbook, "Save");Dispatch.call(workbook, "Close", new Variant(f));} catch (Exception e) {e.printStackTrace();} finally {if(quitXl){releaseSource();}}}/*** 释放资源*/public static void releaseSource(){if(xl!=null){xl.invoke("Quit", new Variant[] {});xl = null;}workbooks = null;ComThread.Release();System.gc();}/*** 添加新的工作表(sheet),(添加后为默认为当前激活的工作表)*/public Dispatch addSheet() {return Dispatch.get(Dispatch.get(workbook, "sheets").toDispatch(), "add").toDispatch();}/*** 修改当前工作表的名字* @param newName*/public void modifyCurrentSheetName(String newName) {Dispatch.put(getCurrentSheet(), "name", newName);}/*** 得到当前工作表的名字* @return*/public String getCurrentSheetName() {return Dispatch.get(getCurrentSheet(), "name").toString();}/*** 得到工作薄的名字* @return*/public String getWorkbookName() {if(workbook==null)return null;return Dispatch.get(workbook, "name").toString();}/*** 得到sheets的集合对象* @return*/public Dispatch getSheets() {if(sheets==null)sheets = Dispatch.get(workbook, "sheets").toDispatch();return sheets;}/*** 得到当前sheet* @return*/public Dispatch getCurrentSheet() {currentSheet = Dispatch.get(workbook, "ActiveSheet").toDispatch();return currentSheet;}/*** 通过工作表名字得到工作表* @param name sheetName* @return*/public Dispatch getSheetByName(String name) {return Dispatch.invoke(getSheets(), "Item", Dispatch.Get, new Object[]{name}, new int[1]).toDispatch();}/*** 通过工作表索引得到工作表(第一个工作簿index为1)* @param index* @return sheet对象*/public Dispatch getSheetByIndex(Integer index) {return Dispatch.invoke(getSheets(), "Item", Dispatch.Get, new Object[]{index}, new int[1]).toDispatch();}/*** 得到sheet的总数* @return*/public int getSheetCount() {int count = Dispatch.get(getSheets(), "count").toInt();return count;}/*** 调用excel宏* @param macroName 宏名*/public void callMacro(String macroName){Dispatch.call(xl, "Run",new Variant(macroName));}/*** 单元格写入值* @param sheet 被操作的sheet* @param position 单元格位置,如:C1* @param type 值的属性如:value* @param value*/public void setValue(Dispatch sheet, String position, String type, Object value) {Dispatch cell = Dispatch.invoke(sheet, "Range",Dispatch.Get, new Object[] { position }, new int[1]).toDispatch();Dispatch.put(cell, type, value);}/*** 单元格读取值* @param position 单元格位置,如: C1* @param sheet* @return*/public Variant getValue(String position, Dispatch sheet) { Dispatch cell = Dispatch.invoke(sheet, "Range", Dispatch.Get, new Object[] { position }, new int[1]).toDispatch();Variant value = Dispatch.get(cell, "Value");return value;}private void initComponents(){workbook = null;currentSheet = null;sheets = null;}}。
如何利用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方法,给属性赋值。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
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())。