java word操作总结

需要 jadoc.jar  下载有些慢 是倒计时下载 大概5秒后开始下载. 
http://sourceforge.net/projects/jacob-project/files/jacob-project/1.16-M1/jacob-1.16-M1.zip/download?source=files 
下载完后 需要把 jacob-1.16-M1-x86.dll 放在system32/下面 
因为doc文件不开放 java不可以直接操作. 

Java代码   收藏代码
  1. package com.mybook.demo;  
  2.   
  3. import com.jacob.activeX.ActiveXComponent;  
  4. import com.jacob.com.Dispatch;  
  5. import com.jacob.com.Variant;  
  6.   
  7. public class Words {  
  8.       
  9.     public static void main(String[] args){  
  10.           
  11.     }  
  12.       
  13.       
  14.     // 代表一个word 程序  
  15.     private ActiveXComponent MsWordApp = null;  
  16.     // 代表进行处理的word 文档  
  17.     private Dispatch document = null;  
  18.       
  19.     public Words() {  
  20.         // Open Word if we/'ve not done it already  
  21.         if (MsWordApp == null) {  
  22.             MsWordApp = new ActiveXComponent("Word.Application");  
  23.         }  
  24.     }  
  25.       
  26.     /** 
  27.      *  设置是否在前台打开 word 程序 , 
  28.      * @param visible 
  29.      */  
  30.     public void setVisible(boolean visible) {  
  31.         MsWordApp.setProperty("Visible"new Variant(visible));  
  32.         // 这一句作用相同  
  33.         // Dispatch.put(MsWordApp, "Visible", new Variant(visible));  
  34.     }  
  35.       
  36.     /** 
  37.      * 创建一个新文档 
  38.      */  
  39.     public void createNewDocument() {  
  40.         // Find the Documents collection object maintained by Word  
  41.         // documents表示word的所有文档窗口,(word是多文档应用程序)  
  42.         Dispatch documents = Dispatch.get(MsWordApp, "Documents").toDispatch();  
  43.         // Call the Add method of the Documents collection to create  
  44.         // a new document to edit  
  45.         document = Dispatch.call(documents, "Add").toDispatch();  
  46.     }  
  47.       
  48.     /** 
  49.      *  打开一个存在的word文档,并用document 引用 引用它 
  50.      * @param wordFilePath 
  51.      */  
  52.     public void openFile(String wordFilePath) {  
  53.         // Find the Documents collection object maintained by Word  
  54.         // documents表示word的所有文档窗口,(word是多文档应用程序)  
  55.         Dispatch documents = Dispatch.get(MsWordApp, "Documents").toDispatch();  
  56.         document = Dispatch.call(documents, "Open", wordFilePath,  
  57.                 new Variant(true)/* 是否进行转换ConfirmConversions */,  
  58.                 new Variant(false)/* 是否只读 */).toDispatch();  
  59.         // document = Dispatch.invoke(documents, "Open", Dispatch.Method,  
  60.         // new Object[] { wordFilePath, new Variant(true),  
  61.         // new Variant(false)  
  62.         // }, new int[1]).toDispatch();  
  63.     }  
  64.       
  65.   
  66.     /** 
  67.      *  向 document 中插入文本内容 
  68.      * @param textToInsert 
  69.      */  
  70.     public void insertText(String textToInsert) {  
  71.         // Get the current selection within Word at the moment.  
  72.         // a new document has just been created then this will be at  
  73.         // the top of the new doc 获得选 中的内容,如果是一个新创建的文件,因里面无内容,则光标应处于文件开头处  
  74.         Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch();  
  75.         // 取消选中,应该就是移动光标 ,否则 新添加的内容会覆盖选中的内容  
  76.         Dispatch.call(selection, "MoveRight"new Variant(1), new Variant(1));  
  77.         // Put the specified text at the insertion point  
  78.         Dispatch.put(selection, "Text", textToInsert);  
  79.         // 取消选中,应该就是移动光标  
  80.         Dispatch.call(selection, "MoveRight"new Variant(1), new Variant(1));  
  81.     }  
  82.   
  83.     // 向文档中添加 一个图片,  
  84.         public void insertJpeg(String jpegFilePath) {  
  85.             Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch();  
  86.             Dispatch image = Dispatch.get(selection, "InLineShapes").toDispatch();  
  87.             Dispatch.call(image, "AddPicture", jpegFilePath);  
  88.         }  
  89.           
  90.         // 段落的处理,插入格式化的文本  
  91.         public void insertFormatStr(String text) {  
  92.             Dispatch wordContent = Dispatch.get(document, "Content").toDispatch(); // 取得word文件的内容  
  93.             Dispatch.call(wordContent, "InsertAfter", text);// 插入一个段落到最后  
  94.             Dispatch paragraphs = Dispatch.get(wordContent, "Paragraphs")  
  95.                     .toDispatch(); // 所有段落  
  96.             int paragraphCount = Dispatch.get(paragraphs, "Count").changeType(  
  97.                     Variant.VariantInt).getInt();// 一共的段落数  
  98.             // 找到刚输入的段落,设置格式  
  99.             Dispatch lastParagraph = Dispatch.call(paragraphs, "Item",  
  100.                     new Variant(paragraphCount)).toDispatch(); // 最后一段(也就是刚插入的)  
  101.             // Range 对象表示文档中的一个连续范围,由一个起始字符位置和一个终止字符位置定义  
  102.             Dispatch lastParagraphRange = Dispatch.get(lastParagraph, "Range")  
  103.                     .toDispatch();  
  104.             Dispatch font = Dispatch.get(lastParagraphRange, "Font").toDispatch();  
  105.             Dispatch.put(font, "Bold"new Variant(true)); // 设置为黑体  
  106.             Dispatch.put(font, "Italic"new Variant(true)); // 设置为斜体  
  107.             Dispatch.put(font, "Name"new Variant("宋体")); //  
  108.             Dispatch.put(font, "Size"new Variant(12)); // 小四  
  109.             Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch();  
  110.             Dispatch.call(selection, "TypeParagraph");// 插入一个空行  
  111.             Dispatch alignment = Dispatch.get(selection, "ParagraphFormat")  
  112.                     .toDispatch();// 段落格式  
  113.             Dispatch.put(alignment, "Alignment""2"); // (1:置中 2:靠右 3:靠左)  
  114.         }  
  115.         // word 中在对表格进行遍历的时候 ,是先列后行 先column 后cell  
  116.         // 另外下标从1开始  
  117.         public void insertTable(String tableTitle, int row, int column) {  
  118.             Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch(); // 输入内容需要的对象  
  119.             Dispatch.call(selection, "TypeText", tableTitle); // 写入标题内容 // 标题格行  
  120.             Dispatch.call(selection, "TypeParagraph"); // 空一行段落  
  121.             Dispatch.call(selection, "TypeParagraph"); // 空一行段落  
  122.             Dispatch.call(selection, "MoveDown"); // 游标往下一行  
  123.             // 建立表格  
  124.             Dispatch tables = Dispatch.get(document, "Tables").toDispatch();  
  125.             // int count = Dispatch.get(tables,  
  126.             // "Count").changeType(Variant.VariantInt).getInt(); // document中的表格数量  
  127.             // Dispatch table = Dispatch.call(tables, "Item", new Variant(  
  128.             // 1)).toDispatch();//文档中第一个表格  
  129.             Dispatch range = Dispatch.get(selection, "Range").toDispatch();// /当前光标位置或者选中的区域  
  130.             Dispatch newTable = Dispatch.call(tables, "Add", range,  
  131.                     new Variant(row), new Variant(column), new Variant(1))  
  132.                     .toDispatch(); // 设置row,column,表格外框宽度  
  133.             Dispatch cols = Dispatch.get(newTable, "Columns").toDispatch(); // 此表的所有列,  
  134.             int colCount = Dispatch.get(cols, "Count").changeType(  
  135.                     Variant.VariantInt).getInt();// 一共有多少列 实际上这个数==column  
  136.             System.out.println(colCount + "列");  
  137.             for (int i = 1; i <= colCount; i++) { // 循环取出每一列  
  138.                 Dispatch col = Dispatch.call(cols, "Item"new Variant(i))  
  139.                         .toDispatch();  
  140.                 Dispatch cells = Dispatch.get(col, "Cells").toDispatch();// 当前列中单元格  
  141.                 int cellCount = Dispatch.get(cells, "Count").changeType(  
  142.                         Variant.VariantInt).getInt();// 当前列中单元格数 实际上这个数等于row  
  143.                 for (int j = 1; j <= cellCount; j++) {// 每一列中的单元格数  
  144.                     // Dispatch cell = Dispatch.call(cells, "Item", new  
  145.                     // Variant(j)).toDispatch(); //当前单元格  
  146.                     // Dispatch cell = Dispatch.call(newTable, "Cell", new  
  147.                     // Variant(j) , new Variant(i) ).toDispatch(); //取单元格的另一种方法  
  148.                     // Dispatch.call(cell, "Select");//选中当前单元格  
  149.                     // Dispatch.put(selection, "Text",  
  150.                     // "第"+j+"行,第"+i+"列");//往选中的区域中填值,也就是往当前单元格填值  
  151.                     putTxtToCell(newTable, j, i, "第" + j + "行,第" + i + "列");// 与上面四句的作用相同  
  152.                 }  
  153.             }  
  154.         }  
  155.         /** */  
  156.         /** 
  157.          * 在指定的单元格里填写数据 
  158.          * 
  159.          * @param tableIndex 
  160.          * @param cellRowIdx 
  161.          * @param cellColIdx 
  162.          * @param txt 
  163.          */  
  164.         public void putTxtToCell(Dispatch table, int cellRowIdx, int cellColIdx,  
  165.                 String txt) {  
  166.             Dispatch cell = Dispatch.call(table, "Cell"new Variant(cellRowIdx),  
  167.                     new Variant(cellColIdx)).toDispatch();  
  168.             Dispatch.call(cell, "Select");  
  169.             Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch(); // 输入内容需要的对象  
  170.             Dispatch.put(selection, "Text", txt);  
  171.         }  
  172.         /** */  
  173.         /** 
  174.          * 在指定的单元格里填写数据 
  175.          * 
  176.          * @param tableIndex 
  177.          * @param cellRowIdx 
  178.          * @param cellColIdx 
  179.          * @param txt 
  180.          */  
  181.         public void putTxtToCell(int tableIndex, int cellRowIdx, int cellColIdx,  
  182.                 String txt) {  
  183.             // 所有表格  
  184.             Dispatch tables = Dispatch.get(document, "Tables").toDispatch();  
  185.             // 要填充的表格  
  186.             Dispatch table = Dispatch.call(tables, "Item"new Variant(tableIndex))  
  187.                     .toDispatch();  
  188.             Dispatch cell = Dispatch.call(table, "Cell"new Variant(cellRowIdx),  
  189.                     new Variant(cellColIdx)).toDispatch();  
  190.             Dispatch.call(cell, "Select");  
  191.             Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch(); // 输入内容需要的对象  
  192.             Dispatch.put(selection, "Text", txt);  
  193.         }  
  194.         // 合并两个单元格  
  195.         public void mergeCell(Dispatch cell1, Dispatch cell2) {  
  196.             Dispatch.call(cell1, "Merge", cell2);  
  197.         }  
  198.         public void mergeCell(Dispatch table, int row1, int col1, int row2, int col2) {  
  199.             Dispatch cell1 = Dispatch.call(table, "Cell"new Variant(row1),  
  200.                     new Variant(col1)).toDispatch();  
  201.             Dispatch cell2 = Dispatch.call(table, "Cell"new Variant(row2),  
  202.                     new Variant(col2)).toDispatch();  
  203.             mergeCell(cell1, cell2);  
  204.         }  
  205.         public void mergeCellTest() {  
  206.             Dispatch tables = Dispatch.get(document, "Tables").toDispatch();  
  207.             int tableCount = Dispatch.get(tables, "Count").changeType(  
  208.                     Variant.VariantInt).getInt(); // document中的表格数量  
  209.             Dispatch table = Dispatch.call(tables, "Item"new Variant(tableCount))  
  210.                     .toDispatch();// 文档中最后一个table  
  211.             mergeCell(table, 1112);// 将table 中x=1,y=1 与x=1,y=2的两个单元格合并  
  212.         }  
  213.         // ========================================================  
  214.         /** */  
  215.         /** 
  216.          * 把选定的内容或光标插入点向上移动 
  217.          * 
  218.          * @param pos 
  219.          *            移动的距离 
  220.          */  
  221.         public void moveUp(int pos) {  
  222.             Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch(); // 输入内容需要的对象  
  223.             for (int i = 0; i < pos; i++) {  
  224.                 // MoveDown MoveLeft moveRight  
  225.                 // moveStart ( Dispatch.call(selection, "HomeKey", new Variant(6));  
  226.                 // )  
  227.                 // moveEnd Dispatch.call(selection, "EndKey", new Variant(6));  
  228.                 Dispatch.call(selection, "MoveUp");  
  229.             }  
  230.         }  
  231.         /** */  
  232.         /** 
  233.          * 从选定内容或插入点开始查找文本 
  234.          * 
  235.          * @param toFindText 
  236.          *            要查找的文本 
  237.          * @return boolean true-查找到并选中该文本,false-未查找到文本 
  238.          */  
  239.         public boolean find(String toFindText) {  
  240.             if (toFindText == null || toFindText.equals(""))  
  241.                 return false;  
  242.             Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch(); // 输入内容需要的对象  
  243.             // 从selection所在位置开始查询  
  244.             Dispatch find = Dispatch.call(selection, "Find").toDispatch();  
  245.             // 设置要查找的内容  
  246.             Dispatch.put(find, "Text", toFindText);  
  247.             // 向前查找  
  248.             Dispatch.put(find, "Forward""True");  
  249.             // 设置格式  
  250.             Dispatch.put(find, "Format""True");  
  251.             // 大小写匹配  
  252.             Dispatch.put(find, "MatchCase""True");  
  253.             // 全字匹配  
  254.             Dispatch.put(find, "MatchWholeWord""True");  
  255.             // 查找并选中  
  256.             return Dispatch.call(find, "Execute").getBoolean();  
  257.         }  
  258.         /** */  
  259.         /** 
  260.          * 把选定选定内容设定为替换文本 
  261.          * 
  262.          * @param toFindText 
  263.          *            查找字符串 
  264.          * @param newText 
  265.          *            要替换的内容 
  266.          * @return 
  267.          */  
  268.         public boolean replaceText(String toFindText, String newText) {  
  269.             if (!find(toFindText))  
  270.                 return false;  
  271.             Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch(); // 输入内容需要的对象  
  272.             Dispatch.put(selection, "Text", newText);  
  273.             return true;  
  274.         }  
  275.         public void printFile() {  
  276.             // Just print the current document to the default printer  
  277.             Dispatch.call(document, "PrintOut");  
  278.         }  
  279.         // 保存文档的更改  
  280.         public void save() {  
  281.             Dispatch.call(document, "Save");  
  282.         }  
  283.         public void saveFileAs(String filename) {  
  284.             Dispatch.call(document, "SaveAs", filename);  
  285.         }  
  286.         public void closeDocument() {  
  287.             // Close the document without saving changes  
  288.             // 0 = wdDoNotSaveChanges  
  289.             // -1 = wdSaveChanges  
  290.             // -2 = wdPromptToSaveChanges  
  291.             Dispatch.call(document, "Close"new Variant(0));  
  292.             document = null;  
  293.         }  
  294.         public void closeWord() {  
  295.             Dispatch.call(MsWordApp, "Quit");  
  296.             MsWordApp = null;  
  297.             document = null;  
  298.         }  
  299.         // 设置wordApp打开后窗口的位置  
  300.         public void setLocation() {  
  301.             Dispatch activeWindow = Dispatch.get(MsWordApp, "Application")  
  302.                     .toDispatch();  
  303.             Dispatch.put(activeWindow, "WindowState"new Variant(1)); // 0=default  
  304.             // 1=maximize  
  305.             // 2=minimize  
  306.             Dispatch.put(activeWindow, "Top"new Variant(0));  
  307.             Dispatch.put(activeWindow, "Left"new Variant(0));  
  308.             Dispatch.put(activeWindow, "Height"new Variant(600));  
  309.             Dispatch.put(activeWindow, "width"new Variant(800));  
  310.         }  
  311.       
  312.       
  313.       
  314. }  




测试类 
Java代码   收藏代码
  1. package com.mybook.demo;  
  2. import java.io.File;  
  3. import com.jacob.activeX.ActiveXComponent;  
  4. import com.jacob.com.Dispatch;  
  5. import com.jacob.com.Variant;  
  6.   
  7. class TestWords {  
  8.     /** 
  9.      * 创建一个新的word 文件 
  10.      */  
  11.     public static void createANewFileTest() {  
  12.         Words wordBean = new Words();  
  13.         // word.openWord(true);// 打开 word 程序  
  14.         wordBean.setVisible(false);  
  15.         wordBean.createNewDocument();// 创建一个新文档  
  16.         wordBean.setLocation();// 设置打开后窗口的位置  
  17.         wordBean.insertText("你好");// 向文档中插入字符  
  18.         wordBean.insertJpeg("D:\\work\\mybook\\Files" + File.separator + "a.jpg"); // 插入图片  
  19.         // 如果 ,想保存文件,下面三句  
  20.          wordBean.saveFileAs("D:\\work\\mybook\\Files\\createANewFileTest.doc");  
  21.          wordBean.closeDocument();  
  22.          wordBean.closeWord();  
  23.     }  
  24.     /** 
  25.      * 打开一个存在的文件 
  26.      * 文件需要存在 
  27.      */  
  28.     public static void openAnExistsFileTest() {  
  29.         Words wordBean = new Words();  
  30.         wordBean.setVisible(false); // 是否前台打开word 程序,或者后台运行  
  31.         wordBean.openFile("D:\\work\\mybook\\Files\\openAnExistsFileTest.doc");  
  32.         wordBean.insertJpeg("D:\\work\\mybook\\Files" + File.separator + "a.jpg"); // 插入图片(注意刚打开的word  
  33.         // ,光标处于开头,故,图片在最前方插入)  
  34.         wordBean.save();  
  35.         wordBean.closeDocument();  
  36.         wordBean.closeWord();  
  37.     }  
  38.     /** 
  39.      * 设置format 
  40.      * @param str 
  41.      */  
  42.     public static void insertFormatStr(String str) {  
  43.         Words wordBean = new Words();  
  44.         wordBean.setVisible(false); // 是否前台打开word 程序,或者后台运行  
  45.         wordBean.createNewDocument();// 创建一个新文档  
  46.         wordBean.insertFormatStr(str);// 插入一个段落,对其中的字体进行了设置  
  47.     }  
  48.       
  49.     /** 
  50.      * 插入表格 
  51.      */  
  52.     public static void insertTableTest() {  
  53.         Words wordBean = new Words();  
  54.         wordBean.setVisible(false); // 是否前台打开word 程序,或者后台运行  
  55.         wordBean.createNewDocument();// 创建一个新文档  
  56.         wordBean.setLocation();  
  57.         wordBean.insertTable("表名"32);  
  58.         wordBean.saveFileAs("D:\\work\\mybook\\Files\\insertTabletest.doc");  
  59.         wordBean.closeDocument();  
  60.         wordBean.closeWord();  
  61.     }  
  62.       
  63.     /** 
  64.      * 合并表格 
  65.      */  
  66.     public static void mergeTableCellTest() {  
  67.         insertTableTest();//生成d://table.doc  
  68.         Words wordBean = new Words();  
  69.         wordBean.setVisible(false); // 是否前台打开word 程序,或者后台运行  
  70.         wordBean.openFile("D:\\work\\mybook\\Files\\insertTabletest.doc");  
  71.         wordBean.mergeCellTest();  
  72.     }  
  73.       
  74.     public static void main(String[] args) {  
  75.         // 进行测试前要保证d://a.jpg 图片文件存在  
  76.          createANewFileTest();//创建一个新文件  
  77.          openAnExistsFileTest();// 打开一个存在 的文件  
  78.          insertFormatStr("格式 化字符串");//对字符串进行一定的修饰  
  79.         insertTableTest();// 创建一个表格  
  80.        mergeTableCellTest();// 对表格中的单元格进行合并  
  81.     }  
  82. }  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值