java jacob 操作word 文档,进行写操作,如生成表格,添加 图片

来源:互联网 发布:郑州大学软件学院2017 编辑:程序博客网 时间:2024/06/05 13:32

jacob-1.15-M3.zip 

jacob-1.15-M3-x86.dll copy 到c:\\windows\system32

引入jacob.jar

示例代码

 

 

[java] view plain copy
 print?
  1. import java.io.File;    
  2. importcom.jacob.activeX.ActiveXComponent;    
  3. import com.jacob.com.Dispatch;    
  4. import com.jacob.com.Variant;    
  5. class WordBean {    
  6.    // 代表一个word 程序    
  7.    private ActiveXComponent MsWordApp = null;    
  8.    // 代表进行处理的word 文档    
  9.    private Dispatch document = null;    
  10.    public WordBean() {    
  11.        // Open Word if we\'ve not done it already    
  12.        if (MsWordApp == null) {    
  13.            MsWordApp = new ActiveXComponent("Word.Application");    
  14.        }    
  15.    }    
  16.    // 设置是否在前台打开 word程序 ,    
  17.    public void setVisible(boolean visible) {    
  18.        MsWordApp.setProperty("Visible"new Variant(visible));    
  19.        // 这一句作用相同    
  20.        // Dispatch.put(MsWordApp, "Visible", newVariant(visible));    
  21.    }    
  22.    // 创建一个新文档    
  23.    public void createNewDocument() {    
  24.        // Find the Documents collection object maintained by Word    
  25.        // documents表示word的所有文档窗口,(word是多文档应用程序)    
  26.        Dispatch documents = Dispatch.get(MsWordApp,"Documents").toDispatch();    
  27.        // Call the Add method of the Documents collection to create    
  28.        // a new document to edit    
  29.        document = Dispatch.call(documents, "Add").toDispatch();    
  30.    }    
  31.    // 打开一个存在的word文档,并用document 引用 引用它    
  32.    public void openFile(String wordFilePath) {    
  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();    
  39.        // document = Dispatch.invoke(documents, "Open",Dispatch.Method,    
  40.        // new Object[] { wordFilePath, new Variant(true),    
  41.        // new Variant(false)    
  42.        // }, new int[1]).toDispatch();    
  43.     }    
  44.    // 向 document 中插入文本内容    
  45.    public void insertText(String textToInsert) {    
  46.        // Get the current selection within Word at the moment.    
  47.        // a new document has just been created then this will be at    
  48.        // the top of the new doc 获得选 中的内容,如果是一个新创建的文件,因里面无内容,则光标应处于文件开头处    
  49.        Dispatch selection = Dispatch.get(MsWordApp,"Selection").toDispatch();    
  50.        // 取消选中,应该就是移动光标 ,否则 新添加的内容会覆盖选中的内容    
  51.        Dispatch.call(selection, "MoveRight"new Variant(1), newVariant(1));    
  52.        // Put the specified text at the insertion point    
  53.        Dispatch.put(selection, "Text", textToInsert);    
  54.        // 取消选中,应该就是移动光标    
  55.        Dispatch.call(selection, "MoveRight"new Variant(1), newVariant(1));    
  56.    }    
  57.    // 向文档中添加 一个图片,    
  58.    public void insertJpeg(String jpegFilePath) {    
  59.        Dispatch selection = Dispatch.get(MsWordApp,"Selection").toDispatch();    
  60.        Dispatch image = Dispatch.get(selection,"InLineShapes").toDispatch();    
  61.        Dispatch.call(image, "AddPicture", jpegFilePath);    
  62.    }    
  63.    // 段落的处理,插入格式化的文本    
  64.    public void insertFormatStr(String text) {    
  65.        Dispatch wordContent = Dispatch.get(document,"Content").toDispatch(); // 取得word文件的内容    
  66.        Dispatch.call(wordContent, "InsertAfter", text);// 插入一个段落到最后    
  67.        Dispatch paragraphs = Dispatch.get(wordContent,"Paragraphs")    
  68.                 .toDispatch(); // 所有段落    
  69.        int paragraphCount = Dispatch.get(paragraphs,"Count").changeType(    
  70.                 Variant.VariantInt).getInt();//一共的段落数    
  71.        // 找到刚输入的段落,设置格式    
  72.        Dispatch lastParagraph = Dispatch.call(paragraphs,"Item",    
  73.                 newVariant(paragraphCount)).toDispatch(); // 最后一段(也就是刚插入的)    
  74.        // Range 对象表示文档中的一个连续范围,由一个起始字符位置和一个终止字符位置定义    
  75.        Dispatch lastParagraphRange = Dispatch.get(lastParagraph,"Range")    
  76.                 .toDispatch();    
  77.        Dispatch font = Dispatch.get(lastParagraphRange,"Font").toDispatch();    
  78.        Dispatch.put(font, "Bold"new Variant(true)); // 设置为黑体    
  79.        Dispatch.put(font, "Italic"new Variant(true)); // 设置为斜体    
  80.        Dispatch.put(font, "Name"new Variant("宋体")); //    
  81.        Dispatch.put(font, "Size"new Variant(12)); // 小四    
  82.        Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch();    
  83.        Dispatch.call(selection, "TypeParagraph");// 插入一个空行    
  84.        Dispatch alignment = Dispatch.get(selection,"ParagraphFormat")    
  85.                 .toDispatch();// 段落格式    
  86.        Dispatch.put(alignment, "Alignment""2"); // (1:置中 2:靠右 3:靠左)    
  87.    }    
  88.    // word 中在对表格进行遍历的时候 ,是先列后行 先column 后cell    
  89.    // 另外下标从1开始    
  90.    public void insertTable(String tableTitle, int row, int column) {    
  91.        Dispatch selection = Dispatch.get(MsWordApp,"Selection").toDispatch(); // 输入内容需要的对象    
  92.        Dispatch.call(selection, "TypeText", tableTitle); // 写入标题内容 // 标题格行    
  93.        Dispatch.call(selection, "TypeParagraph"); // 空一行段落    
  94.        Dispatch.call(selection, "TypeParagraph"); // 空一行段落    
  95.        Dispatch.call(selection, "MoveDown"); // 游标往下一行    
  96.        // 建立表格    
  97.        Dispatch tables = Dispatch.get(document,"Tables").toDispatch();    
  98.        // int count = Dispatch.get(tables,    
  99.        // "Count").changeType(Variant.VariantInt).getInt(); //document中的表格数量    
  100.        // Dispatch table = Dispatch.call(tables, "Item", newVariant(    
  101.        // 1)).toDispatch();//文档中第一个表格    
  102.        Dispatch range = Dispatch.get(selection,"Range").toDispatch();// /当前光标位置或者选中的区域    
  103.        Dispatch newTable = Dispatch.call(tables, "Add", range,    
  104.                 new Variant(row), newVariant(column), new Variant(1))    
  105.                 .toDispatch(); // 设置row,column,表格外框宽度    
  106.        Dispatch cols = Dispatch.get(newTable,"Columns").toDispatch(); // 此表的所有列,    
  107.        int colCount = Dispatch.get(cols, "Count").changeType(    
  108.                 Variant.VariantInt).getInt();//一共有多少列 实际上这个数==column    
  109.        System.out.println(colCount + "列");    
  110.        for (int i = 1; i <= colCount; i++) { // 循环取出每一列    
  111.            Dispatch col = Dispatch.call(cols, "Item", newVariant(i))    
  112.                     .toDispatch();    
  113.            Dispatch cells = Dispatch.get(col, "Cells").toDispatch();// 当前列中单元格    
  114.            int cellCount = Dispatch.get(cells, "Count").changeType(    
  115.                     Variant.VariantInt).getInt();//当前列中单元格数 实际上这个数等于row    
  116.            for (int j = 1; j <= cellCount; j++) {// 每一列中的单元格数    
  117.                 // Dispatch cell =Dispatch.call(cells, "Item", new    
  118.                 // Variant(j)).toDispatch(); //当前单元格    
  119.                 // Dispatch cell =Dispatch.call(newTable, "Cell", new    
  120.                 // Variant(j) , new Variant(i)).toDispatch(); //取单元格的另一种方法    
  121.                 // Dispatch.call(cell,"Select");//选中当前单元格    
  122.                 // Dispatch.put(selection,"Text",    
  123.                // "第"+j+"行,第"+i+"列");//往选中的区域中填值,也就是往当前单元格填值    
  124.                 putTxtToCell(newTable, j, i,"第" + j +"行,第" + i+ "列");// 与上面四句的作用相同    
  125.            }    
  126.        }    
  127.    }    


   /** */ 

  

[java] view plain copy
 print?
  1. /**  
  2.    * 在指定的单元格里填写数据  
  3.    *  
  4.    * @param tableIndex  
  5.    * @param cellRowIdx  
  6.    * @param cellColIdx  
  7.    * @param txt  
  8.    */   
  9.   public void putTxtToCell(Dispatch table, int cellRowIdx, intcellColIdx,    
  10.           String txt) {    
  11.       Dispatch cell = Dispatch.call(table, "Cell", newVariant(cellRowIdx),    
  12.                newVariant(cellColIdx)).toDispatch();    
  13.       Dispatch.call(cell, "Select");    
  14.       Dispatch selection = Dispatch.get(MsWordApp,"Selection").toDispatch(); // 输入内容需要的对象    
  15.       Dispatch.put(selection, "Text", txt);    
  16.   }    
  17.   /** */   
  18.   /**  
  19.    * 在指定的单元格里填写数据  
  20.    *  
  21.    * @param tableIndex  
  22.    * @param cellRowIdx  
  23.    * @param cellColIdx  
  24.    * @param txt  
  25.    */   
  26.   public void putTxtToCell(int tableIndex, int cellRowIdx, intcellColIdx,    
  27.           String txt) {    
  28.       // 所有表格    
  29.       Dispatch tables = Dispatch.get(document,"Tables").toDispatch();    
  30.       // 要填充的表格    
  31.       Dispatch table = Dispatch.call(tables, "Item", newVariant(tableIndex))    
  32.                .toDispatch();    
  33.       Dispatch cell = Dispatch.call(table, "Cell", newVariant(cellRowIdx),    
  34.                newVariant(cellColIdx)).toDispatch();    
  35.       Dispatch.call(cell, "Select");    
  36.       Dispatch selection = Dispatch.get(MsWordApp,"Selection").toDispatch(); // 输入内容需要的对象    
  37.       Dispatch.put(selection, "Text", txt);    
  38.   }    
  39.   // 合并两个单元格    
  40.   public void mergeCell(Dispatch cell1, Dispatch cell2) {    
  41.       Dispatch.call(cell1, "Merge", cell2);    
  42.   }    
  43.   public void mergeCell(Dispatch table, int row1, int col1, int row2, intcol2) {    
  44.       Dispatch cell1 = Dispatch.call(table, "Cell", newVariant(row1),    
  45.                newVariant(col1)).toDispatch();    
  46.       Dispatch cell2 = Dispatch.call(table, "Cell", newVariant(row2),    
  47.               newVariant(col2)).toDispatch();    
  48.       mergeCell(cell1, cell2);    
  49.   }    
  50.   public void mergeCellTest() {    
  51.       Dispatch tables = Dispatch.get(document,"Tables").toDispatch();    
  52.       int tableCount = Dispatch.get(tables, "Count").changeType(    
  53.                Variant.VariantInt).getInt();// document中的表格数量    
  54.       Dispatch table = Dispatch.call(tables, "Item", newVariant(tableCount))    
  55.                .toDispatch();// 文档中最后一个table    
  56.       mergeCell(table, 1112);// 将table 中x=1,y=1 与x=1,y=2的两个单元格合并    
  57.   }    

  

[java] view plain copy
 print?
  1.  /**  
  2.     * 把选定的内容或光标插入点向上移动  
  3.     *  
  4.     * @param pos  
  5.     *            移动的距离  
  6.     */   
  7.    public void moveUp(int pos) {     
  8.        Dispatch selection = Dispatch.get(MsWordApp,"Selection").toDispatch(); // 输入内容需要的对象    
  9.        for (int i = 0; i < pos; i++) {    
  10.            // MoveDown MoveLeft moveRight    
  11.            // moveStart ( Dispatch.call(selection, "HomeKey", new Variant(6));    
  12.            // )    
  13.            // moveEnd Dispatch.call(selection, "EndKey", newVariant(6));    
  14.            Dispatch.call(selection, "MoveUp");    
  15.        }    
  16.    }    
  17.    /** */   
  18.    /**  
  19.     * 从选定内容或插入点开始查找文本  
  20.     *  
  21.     * @param toFindText  
  22.     *            要查找的文本  
  23.     * @return boolean true-查找到并选中该文本,false-未查找到文本  
  24.     */   
  25.    public boolean find(String toFindText) {    
  26.        if (toFindText == null || toFindText.equals(""))    
  27.            return false;    
  28.        Dispatch selection = Dispatch.get(MsWordApp,"Selection").toDispatch(); // 输入内容需要的对象    
  29.        // 从selection所在位置开始查询    
  30.        Dispatch find = Dispatch.call(selection,"Find").toDispatch();    
  31.        // 设置要查找的内容    
  32.        Dispatch.put(find, "Text", toFindText);    
  33.        // 向前查找    
  34.        Dispatch.put(find, "Forward""True");    
  35.        // 设置格式    
  36.        Dispatch.put(find, "Format""True");    
  37.        // 大小写匹配    
  38.        Dispatch.put(find, "MatchCase""True");    
  39.        // 全字匹配    
  40.        Dispatch.put(find, "MatchWholeWord""True");    
  41.        // 查找并选中    
  42.        return Dispatch.call(find, "Execute").getBoolean();    
  43.    }    
  44.    /** */   
  45.    /**  
  46.     * 把选定选定内容设定为替换文本  
  47.     *  
  48.     * @param toFindText  
  49.     *            查找字符串  
  50.     * @param newText  
  51.     *            要替换的内容  
  52.     * @return  
  53.     */   
  54.    public boolean replaceText(String toFindText, String newText) {    
  55.        if (!find(toFindText))    
  56.            return false;    
  57.        Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch();// 输入内容需要的对象    
  58.        Dispatch.put(selection, "Text", newText);    
  59.        return true;    
  60.    }    
  61.    public void printFile() {    
  62.        // Just print the current document to the default printer    
  63.        Dispatch.call(document, "PrintOut");    
  64.    }    
  65.    // 保存文档的更改    
  66.    public void save() {    
  67.        Dispatch.call(document, "Save");    
  68.    }    
  69.    public void saveFileAs(String filename) {    
  70.        Dispatch.call(document, "SaveAs", filename);    
  71.    }    
  72.    public void closeDocument() {    
  73.        // Close the document without saving changes    
  74.        // 0 = wdDoNotSaveChanges    
  75.        // -1 = wdSaveChanges    
  76.        // -2 = wdPromptToSaveChanges    
  77.        Dispatch.call(document, "Close"new Variant(0));    
  78.        document = null;    
  79.    }    
  80.    public void closeWord() {    
  81.        Dispatch.call(MsWordApp, "Quit");    
  82.        MsWordApp = null;    
  83.        document = null;    
  84.    }    
  85.    // 设置wordApp打开后窗口的位置    
  86.    public void setLocation() {    
  87.        Dispatch activeWindow = Dispatch.get(MsWordApp,"Application")    
  88.                 .toDispatch();    
  89.        Dispatch.put(activeWindow, "WindowState"new Variant(1)); //0=default    
  90.        // 1=maximize    
  91.        // 2=minimize    
  92.        Dispatch.put(activeWindow, "Top"new Variant(0));    
  93.        Dispatch.put(activeWindow, "Left"new Variant(0));    
  94.        Dispatch.put(activeWindow, "Height"new Variant(600));    
  95.        Dispatch.put(activeWindow, "width"new Variant(800));    
  96.    }    
  97. }    
  98. public class JacobTest2 {    
  99.    public static void createANewFileTest() {    
  100.        WordBean wordBean = new WordBean();    
  101.        // word.openWord(true);// 打开 word 程序    
  102.        wordBean.setVisible(true);    
  103.        wordBean.createNewDocument();// 创建一个新文档    
  104.        wordBean.setLocation();// 设置打开后窗口的位置    
  105.        wordBean.insertText("你好");// 向文档中插入字符    
  106.        wordBean.insertJpeg("D:" + File.separator + "a.jpg");// 插入图片    
  107.        // 如果 ,想保存文件,下面三句    
  108.        // word.saveFileAs("d:\\a.doc");    
  109.        // word.closeDocument();    
  110.        // word.closeWord();    
  111.    }    
  112.    public static void openAnExistsFileTest() {    
  113.        WordBean wordBean = new WordBean();    
  114.        wordBean.setVisible(true); // 是否前台打开word 程序,或者后台运行    
  115.        wordBean.openFile("d:\\a.doc");    
  116.        wordBean.insertJpeg("D:" + File.separator +"a.jpg"); // 插入图片(注意刚打开的word    
  117.        // ,光标处于开头,故,图片在最前方插入)    
  118.        wordBean.save();    
  119.        wordBean.closeDocument();    
  120.        wordBean.closeWord();    
  121.    }    
  122.    public static void insertFormatStr(String str) {    
  123.        WordBean wordBean = new WordBean();    
  124.        wordBean.setVisible(true); // 是否前台打开word 程序,或者后台运行    
  125.        wordBean.createNewDocument();// 创建一个新文档    
  126.        wordBean.insertFormatStr(str);// 插入一个段落,对其中的字体进行了设置    
  127.    }    
  128.    public static void insertTableTest() {    
  129.        WordBean wordBean = new WordBean();    
  130.        wordBean.setVisible(true); // 是否前台打开word 程序,或者后台运行    
  131.        wordBean.createNewDocument();// 创建一个新文档    
  132.        wordBean.setLocation();    
  133.        wordBean.insertTable("表名"32);    
  134.        wordBean.saveFileAs("d:\\table.doc");    
  135.        wordBean.closeDocument();    
  136.        wordBean.closeWord();    
  137.    }    
  138.    public static void mergeTableCellTest() {    
  139.        insertTableTest();//生成d:\\table.doc    
  140.        WordBean wordBean = new WordBean();    
  141.        wordBean.setVisible(true); // 是否前台打开word 程序,或者后台运行    
  142.        wordBean.openFile("d:\\table.doc");    
  143.        wordBean.mergeCellTest();    
  144.    }    
  145.    public static void main(String[] args) {    
  146.        // 进行测试前要保证d:\\a.jpg图片文件存在    
  147.        // createANewFileTest();//创建一个新文件    
  148.        // openAnExistsFileTest();// 打开一个存在的文件    
  149.        // insertFormatStr("格式 化字符串");//对字符串进行一定的修饰    
  150.        //insertTableTest();// 创建一个表格    
  151.       mergeTableCellTest();// 对表格中的单元格进行合并    
  152.    }    
  153. }   
  154. import java.io.File;  
  155. import com.jacob.activeX.ActiveXComponent;  
  156. import com.jacob.com.Dispatch;  
  157. import com.jacob.com.Variant;  
  158. class WordBean {  
  159.        //代表一个word 程序  
  160.        privateActiveXComponent MsWordApp = null;  
  161.        //代表进行处理的word 文档  
  162.        privateDispatch document = null;  
  163.        publicWordBean() {  
  164.               //Open Word if we\'ve not done it already  
  165.               if(MsWordApp == null) {  
  166.                      MsWordApp= new ActiveXComponent("Word.Application");  
  167.               }  
  168.        }  
  169.        //设置是否在前台打开 word程序 ,  
  170.        publicvoid setVisible(boolean visible) {  
  171.               MsWordApp.setProperty("Visible",new Variant(visible));  
  172.               //这一句作用相同  
  173.               //Dispatch.put(MsWordApp, "Visible", new Variant(visible));  
  174.        }  
  175.        //创建一个新文档  
  176.        publicvoid createNewDocument() {  
  177.               //Find the Documents collection object maintained by Word  
  178.               //documents表示word的所有文档窗口,(word是多文档应用程序)  
  179.               Dispatchdocuments = Dispatch.get(MsWordApp, "Documents").toDispatch();  
  180.               //Call the Add method of the Documents collection to create  
  181.               //a new document to edit  
  182.               document= Dispatch.call(documents, "Add").toDispatch();  
  183.        }  
  184.        //打开一个存在的word文档,并用document 引用 引用它  
  185.        publicvoid openFile(String wordFilePath) {  
  186.               //Find the Documents collection object maintained by Word  
  187.               // documents表示word的所有文档窗口,(word是多文档应用程序)  
  188.               Dispatchdocuments = Dispatch.get(MsWordApp, "Documents").toDispatch();  
  189.               document= Dispatch.call(documents, "Open", wordFilePath,  
  190.                             newVariant(true)/* 是否进行转换ConfirmConversions*/,  
  191.                             newVariant(false)/* 是否只读*/).toDispatch();  
  192.               //document = Dispatch.invoke(documents, "Open", Dispatch.Method,  
  193.               //new Object[] { wordFilePath, new Variant(true),  
  194.               //new Variant(false)  
  195.               //}, new int[1]).toDispatch();  
  196.        }  
  197.        //向 document 中插入文本内容  
  198.        publicvoid insertText(String textToInsert) {  
  199.               //Get the current selection within Word at the moment.  
  200.               //a new document has just been created then this will be at  
  201.               //the top of the new doc 获得选 中的内容,如果是一个新创建的文件,因里面无内容,则光标应处于文件开头处  
  202.               Dispatchselection = Dispatch.get(MsWordApp, "Selection").toDispatch();  
  203.               //取消选中,应该就是移动光标 ,否则 新添加的内容会覆盖选中的内容  
  204.               Dispatch.call(selection,"MoveRight"new Variant(1), new Variant(1));  
  205.               //Put the specified text at the insertion point  
  206.               Dispatch.put(selection,"Text", textToInsert);  
  207.               //取消选中,应该就是移动光标  
  208.               Dispatch.call(selection,"MoveRight"new Variant(1), new Variant(1));  
  209.        }  
  210.        //向文档中添加 一个图片,  
  211.        publicvoid insertJpeg(String jpegFilePath) {  
  212.               Dispatchselection = Dispatch.get(MsWordApp, "Selection").toDispatch();  
  213.               Dispatchimage = Dispatch.get(selection, "InLineShapes").toDispatch();  
  214.               Dispatch.call(image,"AddPicture", jpegFilePath);  
  215.        }  
  216.        //段落的处理,插入格式化的文本  
  217.        publicvoid insertFormatStr(String text) {  
  218.               DispatchwordContent = Dispatch.get(document, "Content").toDispatch(); // 取得word文件的内容  
  219.               Dispatch.call(wordContent,"InsertAfter", text);// 插入一个段落到最后  
  220.               Dispatchparagraphs = Dispatch.get(wordContent, "Paragraphs")  
  221.                             .toDispatch();// 所有段落  
  222.               intparagraphCount = Dispatch.get(paragraphs, "Count").changeType(  
  223.                             Variant.VariantInt).getInt();//一共的段落数  
  224.               //找到刚输入的段落,设置格式  
  225.               DispatchlastParagraph = Dispatch.call(paragraphs, "Item",  
  226.                           newVariant(paragraphCount)).toDispatch(); // 最后一段(也就是刚插入的)  
  227.               //Range 对象表示文档中的一个连续范围,由一个起始字符位置和一个终止字符位置定义  
  228.               DispatchlastParagraphRange = Dispatch.get(lastParagraph, "Range")  
  229.                             .toDispatch();  
  230.               Dispatchfont = Dispatch.get(lastParagraphRange, "Font").toDispatch();  
  231.               Dispatch.put(font,"Bold"new Variant(true)); // 设置为黑体  
  232.               Dispatch.put(font,"Italic"new Variant(true)); // 设置为斜体  
  233.               Dispatch.put(font,"Name"new Variant("宋体")); //  
  234.               Dispatch.put(font, "Size", newVariant(12)); // 小四  
  235.               Dispatchselection = Dispatch.get(MsWordApp, "Selection").toDispatch();  
  236.               Dispatch.call(selection,"TypeParagraph");// 插入一个空行  
  237.               Dispatchalignment = Dispatch.get(selection, "ParagraphFormat")  
  238.                             .toDispatch();//段落格式  
  239.               Dispatch.put(alignment,"Alignment""2"); // (1:置中 2:靠右 3:靠左)  
  240.        }  
  241.        //word 中在对表格进行遍历的时候 ,是先列后行 先column 后cell  
  242.        //另外下标从1开始  
  243.        publicvoid insertTable(String tableTitle, int row, int column) {  
  244.               Dispatchselection = Dispatch.get(MsWordApp, "Selection").toDispatch(); // 输入内容需要的对象  
  245.               Dispatch.call(selection,"TypeText", tableTitle); // 写入标题内容 // 标题格行  
  246.               Dispatch.call(selection,"TypeParagraph"); // 空一行段落  
  247.               Dispatch.call(selection,"TypeParagraph"); // 空一行段落  
  248.               Dispatch.call(selection,"MoveDown"); // 游标往下一行  
  249.               //建立表格  
  250.               Dispatchtables = Dispatch.get(document, "Tables").toDispatch();  
  251.               //int count = Dispatch.get(tables,  
  252.               //"Count").changeType(Variant.VariantInt).getInt(); // document中的表格数量  
  253.               //Dispatch table = Dispatch.call(tables, "Item", new Variant(  
  254.               //1)).toDispatch();//文档中第一个表格  
  255.               Dispatchrange = Dispatch.get(selection, "Range").toDispatch();// /当前光标位置或者选中的区域  
  256.               DispatchnewTable = Dispatch.call(tables, "Add", range,  
  257.                             newVariant(row), new Variant(column), new Variant(1))  
  258.                             .toDispatch();// 设置row,column,表格外框宽度  
  259.               Dispatchcols = Dispatch.get(newTable, "Columns").toDispatch(); // 此表的所有列,  
  260.               intcolCount = Dispatch.get(cols, "Count").changeType(  
  261.                             Variant.VariantInt).getInt();//一共有多少列 实际上这个数==column  
  262.               System.out.println(colCount+ "列");  
  263.               for(int i = 1; i <= colCount; i++) { // 循环取出每一列  
  264.                      Dispatchcol = Dispatch.call(cols, "Item"new Variant(i))  
  265.                                    .toDispatch();  
  266.                      Dispatchcells = Dispatch.get(col, "Cells").toDispatch();// 当前列中单元格  
  267.                      intcellCount = Dispatch.get(cells, "Count").changeType(  
  268.                                    Variant.VariantInt).getInt();//当前列中单元格数 实际上这个数等于row  
  269.                      for(int j = 1; j <= cellCount; j++) {// 每一列中的单元格数  
  270.                             //Dispatch cell = Dispatch.call(cells, "Item", new  
  271.                             //Variant(j)).toDispatch(); //当前单元格  
  272.                             //Dispatch cell = Dispatch.call(newTable, "Cell", new  
  273.                             //Variant(j) , new Variant(i) ).toDispatch(); //取单元格的另一种方法  
  274.                             //Dispatch.call(cell, "Select");//选中当前单元格  
  275.                             //Dispatch.put(selection, "Text",  
  276.                             //"第"+j+"行,第"+i+"列");//往选中的区域中填值,也就是往当前单元格填值  
  277.                             putTxtToCell(newTable,j, i, "第" + j +"行,第" + i+ "列");// 与上面四句的作用相同  
  278.                      }  
  279.               }  
  280.        }  
  281.        /***/  
  282.        /** 
  283.         * 在指定的单元格里填写数据 
  284.         * 
  285.         * @param tableIndex 
  286.         * @param cellRowIdx 
  287.         * @param cellColIdx 
  288.         * @param txt 
  289.         */  
  290.        publicvoid putTxtToCell(Dispatch table, int cellRowIdx, int cellColIdx,  
  291.                      Stringtxt) {  
  292.               Dispatchcell = Dispatch.call(table, "Cell"new Variant(cellRowIdx),  
  293.                             newVariant(cellColIdx)).toDispatch();  
  294.               Dispatch.call(cell,"Select");  
  295.               Dispatchselection = Dispatch.get(MsWordApp, "Selection").toDispatch(); // 输入内容需要的对象  
  296.               Dispatch.put(selection,"Text", txt);  
  297.        }  
  298.        /***/  
  299.        /** 
  300.         * 在指定的单元格里填写数据 
  301.         * 
  302.         * @param tableIndex 
  303.         * @param cellRowIdx 
  304.         * @param cellColIdx 
  305.         * @param txt 
  306.         */  
  307.        publicvoid putTxtToCell(int tableIndex, int cellRowIdx, int cellColIdx,  
  308.                      Stringtxt) {  
  309.               //所有表格  
  310.               Dispatchtables = Dispatch.get(document, "Tables").toDispatch();  
  311.               //要填充的表格  
  312.               Dispatchtable = Dispatch.call(tables, "Item"new Variant(tableIndex))  
  313.                             .toDispatch();  
  314.               Dispatchcell = Dispatch.call(table, "Cell"new Variant(cellRowIdx),  
  315.                             newVariant(cellColIdx)).toDispatch();  
  316.               Dispatch.call(cell,"Select");  
  317.               Dispatchselection = Dispatch.get(MsWordApp, "Selection").toDispatch(); // 输入内容需要的对象  
  318.               Dispatch.put(selection,"Text", txt);  
  319.        }  
  320.        //合并两个单元格  
  321.        publicvoid mergeCell(Dispatch cell1, Dispatch cell2) {  
  322.               Dispatch.call(cell1, "Merge",cell2);  
  323.        }  
  324.        publicvoid mergeCell(Dispatch table, int row1, int col1, int row2, int col2) {  
  325.               Dispatchcell1 = Dispatch.call(table, "Cell"new Variant(row1),  
  326.                             newVariant(col1)).toDispatch();  
  327.               Dispatchcell2 = Dispatch.call(table, "Cell"new Variant(row2),  
  328.                             newVariant(col2)).toDispatch();  
  329.               mergeCell(cell1,cell2);  
  330.        }  
  331.        publicvoid mergeCellTest() {  
  332.               Dispatchtables = Dispatch.get(document, "Tables").toDispatch();  
  333.               inttableCount = Dispatch.get(tables, "Count").changeType(  
  334.                             Variant.VariantInt).getInt();// document中的表格数量  
  335.               Dispatchtable = Dispatch.call(tables, "Item"new Variant(tableCount))  
  336.                             .toDispatch();//文档中最后一个table  
  337.               mergeCell(table,1112);// 将table 中x=1,y=1 与x=1,y=2的两个单元格合并  
  338.        }  
  339.        //========================================================  
  340.        /***/  
  341.        /** 
  342.         * 把选定的内容或光标插入点向上移动 
  343.         * 
  344.         * @param pos 
  345.         *           移动的距离 
  346.         */  
  347.        publicvoid moveUp(int pos) {  
  348.               Dispatchselection = Dispatch.get(MsWordApp, "Selection").toDispatch(); // 输入内容需要的对象  
  349.               for(int i = 0; i < pos; i++) {  
  350.                      //MoveDown MoveLeft moveRight  
  351.                      //moveStart ( Dispatch.call(selection, "HomeKey", new Variant(6));  
  352.                      //)  
  353.                      //moveEnd Dispatch.call(selection, "EndKey", new Variant(6));  
  354.                      Dispatch.call(selection,"MoveUp");  
  355.               }  
  356.        }  
  357.        /***/  
  358.        /** 
  359.         * 从选定内容或插入点开始查找文本 
  360.         * 
  361.         * @param toFindText 
  362.         *           要查找的文本 
  363.         * @return boolean true-查找到并选中该文本,false-未查找到文本 
  364.         */  
  365.        publicboolean find(String toFindText) {  
  366.               if(toFindText == null || toFindText.equals(""))  
  367.                      returnfalse;  
  368.               Dispatchselection = Dispatch.get(MsWordApp, "Selection").toDispatch(); // 输入内容需要的对象  
  369.               //从selection所在位置开始查询  
  370.               Dispatchfind = Dispatch.call(selection, "Find").toDispatch();  
  371.               //设置要查找的内容  
  372.               Dispatch.put(find,"Text", toFindText);  
  373.               //向前查找  
  374.               Dispatch.put(find,"Forward""True");  
  375.               //设置格式  
  376.               Dispatch.put(find,"Format""True");  
  377.               //大小写匹配  
  378.               Dispatch.put(find,"MatchCase""True");  
  379.               //全字匹配  
  380.               Dispatch.put(find,"MatchWholeWord""True");  
  381.               //查找并选中  
  382.               returnDispatch.call(find, "Execute").getBoolean();  
  383.        }  
  384.        /***/  
  385.        /** 
  386.         * 把选定选定内容设定为替换文本 
  387.         * 
  388.         * @param toFindText 
  389.         *           查找字符串 
  390.         * @param newText 
  391.         *           要替换的内容 
  392.         * @return 
  393.         */  
  394.        publicboolean replaceText(String toFindText, String newText) {  
  395.               if(!find(toFindText))  
  396.                      returnfalse;  
  397.               Dispatchselection = Dispatch.get(MsWordApp, "Selection").toDispatch(); // 输入内容需要的对象  
  398.               Dispatch.put(selection,"Text", newText);  
  399.               returntrue;  
  400.        }  
  401.        publicvoid printFile() {  
  402.               //Just print the current document to the default printer  
  403.               Dispatch.call(document,"PrintOut");  
  404.        }  
  405.        //保存文档的更改  
  406.        publicvoid save() {  
  407.               Dispatch.call(document,"Save");  
  408.        }  
  409.        publicvoid saveFileAs(String filename) {  
  410.               Dispatch.call(document,"SaveAs", filename);  
  411.        }  
  412.        publicvoid closeDocument() {  
  413.               //Close the document without saving changes  
  414.               //0 = wdDoNotSaveChanges  
  415.               //-1 = wdSaveChanges  
  416.               //-2 = wdPromptToSaveChanges  
  417.               Dispatch.call(document,"Close"new Variant(0));  
  418.               document= null;  
  419.        }  
  420.        publicvoid closeWord() {  
  421.               Dispatch.call(MsWordApp,"Quit");  
  422.               MsWordApp= null;  
  423.               document= null;  
  424.        }  
  425.        //设置wordApp打开后窗口的位置  
  426.        publicvoid setLocation() {  
  427.               DispatchactiveWindow = Dispatch.get(MsWordApp, "Application")  
  428.                             .toDispatch();  
  429.               Dispatch.put(activeWindow,"WindowState"new Variant(1)); // 0=default  
  430.               //1=maximize  
  431.               //2=minimize  
  432.               Dispatch.put(activeWindow,"Top"new Variant(0));  
  433.               Dispatch.put(activeWindow,"Left"new Variant(0));  
  434.               Dispatch.put(activeWindow,"Height"new Variant(600));  
  435.               Dispatch.put(activeWindow,"width"new Variant(800));  
  436.        }  
  437. }  
  438. public class JacobTest2 {  
  439.        publicstatic void createANewFileTest() {  
  440.               WordBeanwordBean = new WordBean();  
  441.               //word.openWord(true);// 打开 word 程序  
  442.               wordBean.setVisible(true);  
  443.               wordBean.createNewDocument();//创建一个新文档  
  444.               wordBean.setLocation();//设置打开后窗口的位置  
  445.               wordBean.insertText("你好");// 向文档中插入字符  
  446.               wordBean.insertJpeg("D:"+ File.separator + "a.jpg"); // 插入图片  
  447.               //如果 ,想保存文件,下面三句  
  448.               //word.saveFileAs("d:\\a.doc");  
  449.               //word.closeDocument();  
  450.               //word.closeWord();  
  451.        }  
  452.        publicstatic void openAnExistsFileTest() {  
  453.               WordBeanwordBean = new WordBean();  
  454.               wordBean.setVisible(true);// 是否前台打开word 程序,或者后台运行  
  455.               wordBean.openFile("d:\\a.doc");  
  456.               wordBean.insertJpeg("D:"+ File.separator + "a.jpg"); // 插入图片(注意刚打开的word  
  457.               //,光标处于开头,故,图片在最前方插入)  
  458.               wordBean.save();  
  459.               wordBean.closeDocument();  
  460.               wordBean.closeWord();  
  461.        }  
  462.        publicstatic void insertFormatStr(String str) {  
  463.               WordBeanwordBean = new WordBean();  
  464.               wordBean.setVisible(true);// 是否前台打开word 程序,或者后台运行  
  465.               wordBean.createNewDocument();//创建一个新文档  
  466.               wordBean.insertFormatStr(str);//插入一个段落,对其中的字体进行了设置  
  467.        }  
  468.        publicstatic void insertTableTest() {  
  469.               WordBeanwordBean = new WordBean();  
  470.               wordBean.setVisible(true);// 是否前台打开word 程序,或者后台运行  
  471.               wordBean.createNewDocument();//创建一个新文档  
  472.               wordBean.setLocation();  
  473.               wordBean.insertTable("表名"32);  
  474.               wordBean.saveFileAs("d:\\table.doc");  
  475.               wordBean.closeDocument();  
  476.               wordBean.closeWord();  
  477.        }  
  478.        publicstatic void mergeTableCellTest() {  
  479.               insertTableTest();//生成d:\\table.doc  
  480.               WordBeanwordBean = new WordBean();  
  481.               wordBean.setVisible(true);// 是否前台打开word 程序,或者后台运行  
  482.               wordBean.openFile("d:\\table.doc");  
  483.               wordBean.mergeCellTest();  
  484.        }  
  485.        publicstatic void main(String[] args) {  
  486.               //进行测试前要保证d:\\a.jpg图片文件存在  
  487.               //createANewFileTest();//创建一个新文件  
  488.               //openAnExistsFileTest();// 打开一个存在 的文件  
  489.               //insertFormatStr("格式 化字符串");//对字符串进行一定的修饰  
  490.               //insertTableTest();//创建一个表格  
  491.           mergeTableCellTest();// 对表格中的单元格进行合并  
  492.        }  
  493. }  
阅读全文
0 0
原创粉丝点击