java txt 转word_第1页
java txt 转word_第2页
java txt 转word_第3页
java txt 转word_第4页
java txt 转word_第5页
已阅读5页,还剩22页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1、使用JACOB进行Word编程示例 2015年7月2日13:44Jacob项目的官方地址: Http:/官方介绍:    JACOB is a JAVA-COM Bridge that allows you to call COM Automation components from Java. It uses JNI to make native calls to the COM libraries. JACOB runs on x86 and x64 environments supporting 32 bit and 64 bit JVMs它是一个使用jni

2、来调用com组件及其库文件的工具。这里仅介绍处理word文档。 首先要部署其dll文件。jacob-1.14.3-x86.dll 或 jacob-1.14.3-x64.dll,下载的文件解压后即可看到。我是直接将dll文件放在windowssystem32目录下的,方便,当然也有其他做法。其次,就是把其jar文件路径加入Windows路径中。接着就可以在你的Java程序中调用了。我总结下大概有下面几个阶段: 1. 初始化相关参数,代码如下:/ 打开Word应用程序ActiveXComponent app = new Acti

3、veXComponent("Word.Application");/ 设置word不可见app.setProperty("Visible", new Variant(false);/ 打开word文件Dispatch word = app.getProperty("Documents").toDispatch();Dispatch doc = Dispatch.invoke(word, "Open",

4、60;Dispatch.Method, new Object "File Name", new Variant(false), new Variant(false) , new int1).toDispatch();/获取指针Dispatch cursor = app.getProperty("Selection").toDispatch();如上,我们打开了一个名为File Name的word文件,你可能会觉得最后

5、那句看起来很繁琐,是的,有更好的代替方式,如下:Dispatch doc = Dispatch.call(word, "Open", new Variant(false), new Variant(false).toDisptach();这正是Jacob给我们提供的两种调用方式。 2. 处理word文档,如果你先前有VBA相关开发经验,那就简单了。没有的也没事,打开office程序目录下的2052VBAWD10.chm,这里有Word的对象模型的所有记录。接着讲述下Jacob中两种最常

6、用的类型:Variant:这是一种可变的类型,用于Jacob中几乎所有函数的返回值,并可转换为其他任何类型,包括Java基本类型。当然,应该按需要与规则来。Dispatch:Object represents MS level dispatch object. Each instance of this points at some data structure on the MS windows side.就是说可以代表所有对象模型。import java.util.ArrayList;    import java.util.List;  

7、      import com.jacob.activeX.ActiveXComponent;     import .ComThread;     import .Dispatch;     import .Variant;       import org.apache.log4j.Logger;       /* 

8、60;  *     *作用:利用jacob插件生成word 文件!     *     * */   public class DOCWriter            /* 日志记录器 */       static private Logger logger = Logger.getLogger(DOC

9、Writer.class);           /* word文档        *         * 在本类中有两种方式可以进行文档的创建,<br>        * 第一种调用 createNewDocument        * 第二种调用 ope

10、nDocument         */         private Dispatch document = null;            /* word运行程序对象 */         private ActiveXComponent word = null;  &#

11、160;         /* 所有word文档 */         private Dispatch documents = null;            /*        *  Selection 对象 代表窗口或窗格中的当前所选内容。 所选内容代表文档中选定(或突出显示)的区域,如果文档中没有选

12、定任何内容,则代表插入点。        *  每个文档窗格只能有一个Selection 对象,并且在整个应用程序中只能有一个活动的 Selection 对象。        */       private Dispatch selection = null;            /*    &

13、#160;   *         * Range 对象 代表文档中的一个连续区域。 每个 Range 对象由一个起始字符位置和一个终止字符位置定义。        * 说明:与书签在文档中的使用方法类似,Range 对象在 Visual Basic 过程中用来标识文档的特定部分。        * 但与书签不同的是,Range对象只在定义该对象的过程运行时才存在。  

14、;      * Range对象独立于所选内容。也就是说,您可以定义和处理一个范围而无需更改所选内容。还可以在文档中定义多个范围,但每个窗格中只能有一个所选内容。        */       private Dispatch range = null;           /*        * Page

15、Setup 对象 该对象包含文档的所有页面设置属性(如左边距、下边距和纸张大小)。        */       private Dispatch pageSetup = null;           /* 文档中的所有表格对象 */       private Dispatch tables = null;    

16、0;      /* 一个表格对象 */       private Dispatch table = null;           /* 表格所有行对象 */       private Dispatch rows = null;           /* 表格所有列对象 */ 

17、60;     private Dispatch cols = null;           /* 表格指定行对象 */       private Dispatch row = null;           /* 表格指定列对象 */       private Dispatch col = null;

18、           /* 表格中指定的单元格 */       private Dispatch cell = null;                /* 字体 */       private Dispatch font = null;    

19、0;           /* 对齐方式 */       private Dispatch alignment = null;           /*        * 构造方法        */     

20、0; public DOCWriter()                 if(this.word = null)                /* 初始化应用所要用到的对象实例 */            

21、0;  this.word = new ActiveXComponent("Word.Application");                 /* 设置Word文档是否可见,true-可见false-不可见 */               this.word.setProperty

22、("Visible",new Variant(true);                /* 禁用宏 */               this.word.setProperty("AutomationSecurity", new Variant(3);   

23、;                     if(this.documents = null)                this.documents = word.getProperty("Documents").toDispatch();  

24、                             /*        * 设置页面方向和页边距        *        * param orientation  

25、     *            可取值0或1,分别代表横向和纵向        * param leftMargin        *            左边距的值     

26、;   * param rightMargin        *            右边距的值        * param topMargin        *          &#

27、160; 上边距的值        * param buttomMargin        *            下边距的值        */       public void setPageSetup(int orientation, int lef

28、tMargin,int rightMargin, int topMargin, int buttomMargin)                         logger.debug("设置页面方向和页边距.");            if(this.pageS

29、etup = null)                this.getPageSetup();                        Dispatch.put(pageSetup, "Orientation", orientati

30、on);            Dispatch.put(pageSetup, "LeftMargin", leftMargin);            Dispatch.put(pageSetup, "RightMargin", rightMargin);         &

31、#160;  Dispatch.put(pageSetup, "TopMargin", topMargin);            Dispatch.put(pageSetup, "BottomMargin", buttomMargin);                   /*  &

32、#160;      * 打开文件         *         * param inputDoc         *            要打开的文件,全路径       

33、;  * return Dispatch         *            打开的文件         */         public Dispatch openDocument(String inputDoc)    

34、0;            logger.debug("打开Word文档.");            this.document = Dispatch.call(documents,"Open",inputDoc).toDispatch();            t

35、his.getSelection();            this.getRange();            this.getAlignment();            this.getFont();        &

36、#160;   this.getPageSetup();            return this.document;                     /*        * 创建新的文件      

37、;  *         * return Dispache 返回新建文件        */       public Dispatch createNewDocument()                     

38、   logger.debug("创建新的文件.");            this.document = Dispatch.call(documents,"Add").toDispatch();            this.getSelection();       &#

39、160;    this.getRange();            this.getPageSetup();            this.getAlignment();            this.getFont();    &

40、#160;       return this.document;                   /*         * 选定内容         * return Dispatch 选定的范围或插入点     

41、    */         public Dispatch getSelection()                 logger.debug("获取选定范围的插入点.");            this.selection = word.g

42、etProperty("Selection").toDispatch();            return this.selection;                     /*        * 获取当前Document内可以修改的部分<p&

43、gt;<br>        * 前提条件:选定内容必须存在        *         * param selectedContent 选定区域        * return 可修改的对象        */      

44、; public Dispatch getRange()                logger.debug("获取当前Document内可以修改的部分.");            this.range = Dispatch.get(this.selection, "Range").toDispatch();  

45、          return this.range;                   /*        * 获得当前文档的文档页面属性        */       public Dispatch

46、getPageSetup()                         logger.debug("获得当前文档的文档页面属性.");            if(this.document = null)     

47、0;          logger.warn("document对象为空.");                return this.pageSetup;                  

48、60;     this.pageSetup = Dispatch.get(this.document, "PageSetup").toDispatch();            return this.pageSetup;                   /*  

49、0;      * 把选定内容或插入点向上移动         * param count 移动的距离         */         public void moveUp(int count)               

50、  logger.debug("把选定内容或插入点向上移动.");            for(int i = 0;i < count;i+)                 Dispatch.call(this.selection,"MoveUp");     

51、;                           /*         * 把选定内容或插入点向下移动         * param count 移动的距离        

52、 */         public void moveDown(int count)                 logger.debug("把选定内容或插入点向下移动.");            for(int i = 0;i < count;i+)  

53、               Dispatch.call(this.selection,"MoveDown");                                /* 

54、0;       * 把选定内容或插入点向左移动         * param count 移动的距离         */         public void moveLeft(int count)             

55、0;   logger.debug("把选定内容或插入点向左移动.");            for(int i = 0;i < count;i+)                 Dispatch.call(this.selection,"MoveLeft");  &#

56、160;                             /*         * 把选定内容或插入点向右移动         * param count 移动的距离      &#

57、160;  */         public void moveRight(int count)                 logger.debug("把选定内容或插入点向右移动.");            for(int i = 0;i < count

58、;i+)                 Dispatch.call(this.selection,"MoveRight");                              &#

59、160;     /*        * 回车键        */       public void enterDown(int count)                       

60、; logger.debug("按回车键.");            for(int i = 0;i < count;i+)                 Dispatch.call(this.selection, "TypeParagraph");      

61、;                         /*         * 把插入点移动到文件首位置         */         public void moveStart()  

62、;               logger.debug("把插入点移动到文件首位置.");            Dispatch.call(this.selection,"HomeKey",new Variant(6);           &#

63、160;         /*         * 从选定内容或插入点开始查找文本         * param selection 选定内容         * param toFindText 要查找的文本         * return boolea

64、n true-查找到并选中该文本,false-未查找到文本         */         public boolean find(String toFindText)                 logger.debug("从选定内容或插入点开始查找文本"+" 要查找内容: 

65、"+toFindText);            /* 从selection所在位置开始查询 */           Dispatch find = Dispatch.call(this.selection,"Find").toDispatch();           &#

66、160; /* 设置要查找的内容 */           Dispatch.put(find,"Text",toFindText);             /* 向前查找 */           Dispatch.put(find,"Forward","

67、True");             /* 设置格式 */           Dispatch.put(find,"Format","True");             /* 大小写匹配 */    &

68、#160;      Dispatch.put(find,"MatchCase","True");             /* 全字匹配 */           Dispatch.put(find,"MatchWholeWord","True"); 

69、60;           /* 查找并选中 */           return Dispatch.call(find,"Execute").getBoolean();                     /*  

70、;       * 把选定内容替换为设定文本         * param selection 选定内容         * param newText 替换为文本         */         public void replace(String newTe

71、xt)                 logger.debug("把选定内容替换为设定文本.");            /* 设置替换文本 */           Dispatch.put(this.selection,"Text",

72、newText);                     /*         * 全局替换         * param selection 选定内容或起始插入点         * param oldText 要替换的文本

73、         * param replaceObj 替换为文本        */         public void replaceAll(String oldText,Object replaceObj)                 logger.deb

74、ug("全局替换.");            /* 移动到文件开头 */           moveStart();             /* 表格替换方式 */          

75、 String newText = (String) replaceObj;            /* 图片替换方式 */           if(oldText.indexOf("image") != -1 | newText.lastIndexOf(".bmp") != -1 | newText.lastIndexOf(".jpg") !=

76、 -1 | newText.lastIndexOf(".gif") != -1)                 while (find(oldText)                      insertImage(newText);

77、                     Dispatch.call(this.selection,"MoveRight");                        

78、60;         /* 正常替换方式 */           else                 while (find(oldText)             &

79、#160;        replace(newText);                     Dispatch.call(this.selection,"MoveRight");            

80、                                      /*         * 插入图片         * param selectio

81、n 图片的插入点         * param imagePath 图片文件(全路径)         */         public void insertImage(String imagePath)                 logger.d

82、ebug("插入图片.");            Dispatch.call(this.selection, "TypeParagraph");            Dispatch.call(Dispatch.get(this.selection,"InLineShapes").toDispatch(),"AddPictu

83、re",imagePath);                     /*        * 合并表格        *        * param selection 操作对象      

84、60; * param tableIndex 表格起始点        * param fstCellRowIdx 开始行        * param fstCellColIdx 开始列        * param secCellRowIdx 结束行        * param secCellColIdx 结束列    &

85、#160;   */       public void mergeCell(int tableIndex, int fstCellRowIdx, int fstCellColIdx, int secCellRowIdx, int secCellColIdx)               logger.debug("合并单元格.");     &#

86、160;      if(this.table = null)                logger.warn("table对象为空.");                return;     

87、0;                  Dispatch fstCell = Dispatch.call(table, "Cell",new Variant(fstCellRowIdx), new Variant(fstCellColIdx).toDispatch();            Dispatch secCell =

88、 Dispatch.call(table, "Cell",new Variant(secCellRowIdx), new Variant(secCellColIdx).toDispatch();            Dispatch.call(fstCell, "Merge", secCell);                

89、0;  /*        * 想Table对象中插入数值<p>        *     参数形式:ArrayList<String>List.size()为表格的总行数<br>        *     String的length属性值应该与所创建的表格列数相同   &

90、#160;    *         * param selection 插入点        * param tableIndex 表格起始点        * param list 数据内容        */       public void insertToT

91、able(List<String> list)               System.out.println("向Table对象中插入数据.");            logger.debug("向Table对象中插入数据.");        

92、60;   if(list = null | list.size() <= 0)                logger.warn("写出数据集为空.");                return;      

93、60;                 if(this.table = null)                logger.warn("table对象为空.");            

94、    return;                        for(int i = 0; i < list.size(); i+)                String  strs = list.g

95、et(i);                for(int j = 0; j<strs.length; j+)                    /* 遍历表格中每一个单元格,遍历次数与所要填入的内容数量相同 */     

96、60;             Dispatch cell = this.getCell(i+1, j+1);                    /* 选中此单元格 */           &#

97、160;       Dispatch.call(cell, "Select");                    /* 写出内容到此单元格中 */                &#

98、160;  Dispatch.put(this.selection, "Text", strsj);                    /* 移动游标到下一个位置 */                    

99、0;          this.moveDown(1);                        this.enterDown(1);                 &#

100、160; /*        * 在文档中正常插入文字内容        *         * param selection 插入点        * param list 数据内容        */       public voi

101、d insertToDocument(List<String> list)               logger.debug("向Document对象中插入数据.");            if(list = null | list.size() <= 0)       &#

102、160;        logger.warn("写出数据集为空.");                return;                        if

103、(this.document = null)                logger.warn("document对象为空.");                return;           

104、;             for(String str : list)                /* 写出至word中 */               this.applyListTemplate(3, 2); 

105、;               Dispatch.put(this.selection, "Text", str);                this.moveDown(1);           

106、60;    this.enterDown(1);                               /*        * 创建新的表格        *    

107、60;    * param selection 插入点        * param document 文档对象        * param rowCount 行数        * param colCount 列数        * param width 边框数值 0浅色1深色    &#

108、160;   * return 新创建的表格对象        */       public Dispatch createNewTable(int rowCount, int colCount, int width)               logger.debug("创建新的表格.");  

109、0;         if(this.tables = null)                this.getTables();                        this.

110、getRange();            if(rowCount > 0 && colCount > 0)                this.table = Dispatch.call(this.tables,"Add",this.range,new Variant(rowCount),new Var

111、iant(colCount),new Variant(width).toDispatch();                        /* 返回新创建表格 */           return this.table;        

112、0;          /*        * 获取Document对象中的所有Table对象        *         * return 所有Table对象        */       public Dispatch

113、 getTables()                  logger.debug("获取所有表格对象.");            if(this.document = null)              

114、;  logger.warn("document对象为空.");                return this.tables;                        this.tables = Dispatch.g

115、et(this.document, "Tables").toDispatch();            return this.tables;                        /*        * 获取Docum

116、ent中Table的数量        *         * return 表格数量        */       public int getTablesCount()                 &

117、#160;      logger.debug("获取文档中表格数量.");            if(this.tables = null)                this.getTables();       

118、60;                return Dispatch.get(tables, "Count").getInt();                               /*&#

119、160;       * 获取指定序号的Table对象        *         * param tableIndex Table序列        * return        */       public Dispatch getTa

120、ble(int tableIndex)               logger.debug("获取指定表格对象.");            if(this.tables = null)               

121、this.getTables();                        if(tableIndex >= 0)                this.table = Dispatch.call(this.tables, "Item&

122、quot;, new Variant(tableIndex).toDispatch();                        return this.table;                   /*    

123、0;   * 获取表格的总列数        *         * return 总列数        */       public int getTableColumnsCount()               

124、 logger.debug("获取表格总行数.");            if(this.table = null)                logger.warn("table对象为空.");          

125、0;     return 0;                        return Dispatch.get(this.cols,"Count").getInt();                 

126、  /*        * 获取表格的总行数        *         * return 总行数        */       public int getTableRowsCount()         &#

127、160;     logger.debug("获取表格总行数.");            if(this.table = null)                logger.warn("table对象为空.");      

128、          return 0;                        return Dispatch.get(this.rows,"Count").getInt();          

129、0;     /*        * 获取表格列对象        *         * return 列对象        */       public Dispatch getTableColumns()      

130、60;         logger.debug("获取表格行对象.");            if(this.table = null)                logger.warn("table对象为空.");  &

131、#160;             return this.cols;                        this.cols = Dispatch.get(this.table,"Columns").toDispatch();  

132、0;         return this.cols;                      /*        * 获取表格的行对象        *         * return 总行数   

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

最新文档

评论

0/150

提交评论