java调用com组件操作word使用总结(jacob)

来源:互联网 发布:怎么开农村淘宝服务站 编辑:程序博客网 时间:2024/06/06 10:02
  1. 首先需要下载最新的jacob,不一定是帖子上说的1.14.1,接下来就是一下介绍了。缺点必须安装office

    2008-4-27  Edited By DingDangXiaoMa
    运用jacob 来与word 进行交互。
    参考例子:http://www.99inf.net/SoftwareDev/Java/54344.htm 
    例 子做的不错,注释写的也很全。
    配置说明: 
    http://www.danadler.com/jacob/ 
    官方上下载 jacob的包。jacob-1.14.1
    配置:
    1。jacob-1.14.1-x86.dll  文件,加载进系统环境变量 path中。
    2.jacob-1.14.1-x86.dll  文件拷到windows /system32中。
    3.jacob-1.14.1-x86.dll  文件拷到jdk/bin中。
    要不然会有找不到.dll文件的可能。程序就无法运行了。
    下面的这个例子,表示了,把一些字符串写入到指定 的word中。程序可以运行于.java 文件。.jsp 还有servlet 环境下。

  1. import com.jacob.activeX.ActiveXComponent;  
  2. import com.jacob.com.Dispatch;  
  3. import com.jacob.com.Variant;  
  4.   
  5. /** 
  6.  * jacob操作MSword类 
  7.  * @author  
  8.  */  
  9.   
  10. public class WordBean {  
  11.     // word文档  
  12.     private Dispatch doc;  
  13.       
  14.     // word运行程序对象  
  15.     private ActiveXComponent word;  
  16.   
  17.     // 所有word文档集合  
  18.     private Dispatch documents;  
  19.   
  20.     // 选定的范围或插入点  
  21.     private Dispatch selection;  
  22.   
  23.     private boolean saveOnExit = true;  
  24.   
  25.     public WordBean()throws Exception{  
  26.         if (word == null) {  
  27.             word = new ActiveXComponent("Word.Application");  
  28.             word.setProperty("Visible"new Variant(false));    //不可见打开word           
  29.             word.setProperty("AutomationSecurity"new Variant(3)); //禁用宏  
  30.         }  
  31.         if (documents == null)  
  32.             documents = word.getProperty("Documents").toDispatch();  
  33.     }  
  34.       
  35.     /** 
  36.      * 设置退出时参数 
  37.      *  
  38.      * @param saveOnExit 
  39.      *            boolean true-退出时保存文件,false-退出时不保存文件 
  40.      */  
  41.     public void setSaveOnExit(boolean saveOnExit) {  
  42.         this.saveOnExit = saveOnExit;  
  43.     }  
  44.   
  45.     /** 
  46.      * 创建一个新的word文档 
  47.      *  
  48.      */  
  49.     public void createNewDocument() {  
  50.         doc = Dispatch.call(documents, "Add").toDispatch();  
  51.         selection = Dispatch.get(word, "Selection").toDispatch();  
  52.     }  
  53.   
  54.     /** 
  55.      * 打开一个已存在的文档 
  56.      *  
  57.      * @param docPath 
  58.      */  
  59.     public void openDocument(String docPath) {  
  60.         closeDocument();  
  61.         doc = Dispatch.call(documents, "Open", docPath).toDispatch();  
  62.         selection = Dispatch.get(word, "Selection").toDispatch();  
  63.     }  
  64.       
  65.     /** 
  66.      * 打开一个保护文档, 
  67.      * @param docPath-文件全名 
  68.      * @param pwd-密码 
  69.      */  
  70.     public void openDocumentOnlyRead(String docPath, String pwd)throws Exception {  
  71.         closeDocument();  
  72. //      doc = Dispatch.invoke(documents, "Open", Dispatch.Method,   
  73. //              new Object[]{docPath, new Variant(false), new Variant(true), new Variant(true), pwd},   
  74. //              new int[1]).toDispatch();//打开word文件   
  75.         doc =  Dispatch.callN(documents, "Open"new Object[]{docPath, new Variant(false),   
  76.                 new Variant(true), new Variant(true), pwd, ""new Variant(false)}).toDispatch();  
  77.         selection = Dispatch.get(word, "Selection").toDispatch();  
  78.     }  
  79.       
  80.     public void openDocument(String docPath, String pwd)throws Exception {  
  81.         closeDocument();          
  82.         doc =  Dispatch.callN(documents, "Open"new Object[]{docPath, new Variant(false),   
  83.                 new Variant(false), new Variant(true), pwd}).toDispatch();  
  84.         selection = Dispatch.get(word, "Selection").toDispatch();  
  85.     }  
  86.   
  87.     /** 
  88.      * 把选定的内容或插入点向上移动 
  89.      *  
  90.      * @param pos 
  91.      *            移动的距离 
  92.      */  
  93.     public void moveUp(int pos) {  
  94.         if (selection == null)  
  95.             selection = Dispatch.get(word, "Selection").toDispatch();  
  96.         for (int i = 0; i < pos; i++)  
  97.             Dispatch.call(selection, "MoveUp");  
  98.   
  99.     }  
  100.   
  101.     /** 
  102.      * 把选定的内容或者插入点向下移动 
  103.      *  
  104.      * @param pos 
  105.      *            移动的距离 
  106.      */  
  107.     public void moveDown(int pos) {  
  108.         if (selection == null)  
  109.             selection = Dispatch.get(word, "Selection").toDispatch();  
  110.         for (int i = 0; i < pos; i++)  
  111.             Dispatch.call(selection, "MoveDown");  
  112.     }  
  113.   
  114.     /** 
  115.      * 把选定的内容或者插入点向左移动 
  116.      *  
  117.      * @param pos 
  118.      *            移动的距离 
  119.      */  
  120.     public void moveLeft(int pos) {  
  121.         if (selection == null)  
  122.             selection = Dispatch.get(word, "Selection").toDispatch();  
  123.         for (int i = 0; i < pos; i++) {  
  124.             Dispatch.call(selection, "MoveLeft");  
  125.         }  
  126.     }  
  127.   
  128.     /** 
  129.      * 把选定的内容或者插入点向右移动 
  130.      *  
  131.      * @param pos 
  132.      *            移动的距离 
  133.      */  
  134.     public void moveRight(int pos) {  
  135.         if (selection == null)  
  136.             selection = Dispatch.get(word, "Selection").toDispatch();  
  137.         for (int i = 0; i < pos; i++)  
  138.             Dispatch.call(selection, "MoveRight");  
  139.     }  
  140.   
  141.     /** 
  142.      * 把插入点移动到文件首位置 
  143.      *  
  144.      */  
  145.     public void moveStart() {  
  146.         if (selection == null)  
  147.             selection = Dispatch.get(word, "Selection").toDispatch();  
  148.         Dispatch.call(selection, "HomeKey"new Variant(6));  
  149.     }  
  150.   
  151.     /** 
  152.      * 从选定内容或插入点开始查找文本 
  153.      *  
  154.      * @param toFindText 
  155.      *            要查找的文本 
  156.      * @return boolean true-查找到并选中该文本,false-未查找到文本 
  157.      */  
  158.     @SuppressWarnings("static-access")  
  159.     public boolean find(String toFindText) {  
  160.         if (toFindText == null || toFindText.equals(""))  
  161.             return false;  
  162.         // 从selection所在位置开始查询  
  163.         Dispatch find = word.call(selection, "Find").toDispatch();  
  164.         // 设置要查找的内容  
  165.         Dispatch.put(find, "Text", toFindText);  
  166.         // 向前查找  
  167.         Dispatch.put(find, "Forward""True");  
  168.         // 设置格式  
  169.         Dispatch.put(find, "Format""True");  
  170.         // 大小写匹配  
  171.         Dispatch.put(find, "MatchCase""True");  
  172.         // 全字匹配  
  173.         Dispatch.put(find, "MatchWholeWord""True");  
  174.         // 查找并选中  
  175.         return Dispatch.call(find, "Execute").getBoolean();  
  176.     }  
  177.   
  178.     /** 
  179.      * 把选定选定内容设定为替换文本 
  180.      *  
  181.      * @param toFindText 
  182.      *            查找字符串 
  183.      * @param newText 
  184.      *            要替换的内容 
  185.      * @return 
  186.      */  
  187.     public boolean replaceText(String toFindText, String newText) {  
  188.         if (!find(toFindText))  
  189.             return false;  
  190.         Dispatch.put(selection, "Text", newText);  
  191.         return true;  
  192.     }  
  193.   
  194.     /** 
  195.      * 全局替换文本 
  196.      *  
  197.      * @param toFindText 
  198.      *            查找字符串 
  199.      * @param newText 
  200.      *            要替换的内容 
  201.      */  
  202.     public void replaceAllText(String toFindText, String newText) {  
  203.         while (find(toFindText)) {  
  204.             Dispatch.put(selection, "Text", newText);  
  205.             Dispatch.call(selection, "MoveRight");  
  206.         }  
  207.     }  
  208.   
  209.     /** 
  210.      * 在当前插入点插入字符串 
  211.      *  
  212.      * @param newText 
  213.      *            要插入的新字符串 
  214.      */  
  215.     public void insertText(String newText) {  
  216.         Dispatch.put(selection, "Text", newText);  
  217.     }  
  218.   
  219.     /** 
  220.      *  
  221.      * @param toFindText 
  222.      *            要查找的字符串 
  223.      * @param imagePath 
  224.      *            图片路径 
  225.      * @return 
  226.      */  
  227.     public boolean replaceImage(String toFindText, String imagePath) {  
  228.         if (!find(toFindText))  
  229.             return false;  
  230.         Dispatch.call(Dispatch.get(selection, "InLineShapes").toDispatch(),  
  231.                 "AddPicture", imagePath);  
  232.         return true;  
  233.     }  
  234.   
  235.     /** 
  236.      * 全局替换图片 
  237.      *  
  238.      * @param toFindText 
  239.      *            查找字符串 
  240.      * @param imagePath 
  241.      *            图片路径 
  242.      */  
  243.     public void replaceAllImage(String toFindText, String imagePath) {  
  244.         while (find(toFindText)) {  
  245.             Dispatch.call(Dispatch.get(selection, "InLineShapes").toDispatch(),  
  246.                     "AddPicture", imagePath);  
  247.             Dispatch.call(selection, "MoveRight");  
  248.         }  
  249.     }  
  250.   
  251.     /** 
  252.      * 在当前插入点插入图片 
  253.      *  
  254.      * @param imagePath 
  255.      *            图片路径 
  256.      */  
  257.     public void insertImage(String imagePath) {  
  258.         Dispatch.call(Dispatch.get(selection, "InLineShapes").toDispatch(),  
  259.                 "AddPicture", imagePath);  
  260.     }  
  261.   
  262.     /** 
  263.      * 合并单元格 
  264.      *  
  265.      * @param tableIndex 
  266.      * @param fstCellRowIdx 
  267.      * @param fstCellColIdx 
  268.      * @param secCellRowIdx 
  269.      * @param secCellColIdx 
  270.      */  
  271.     public void mergeCell(int tableIndex, int fstCellRowIdx, int fstCellColIdx,  
  272.             int secCellRowIdx, int secCellColIdx) {  
  273.         // 所有表格  
  274.         Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();  
  275.         // 要填充的表格  
  276.         Dispatch table = Dispatch.call(tables, "Item"new Variant(tableIndex))  
  277.                 .toDispatch();  
  278.         Dispatch fstCell = Dispatch.call(table, "Cell",  
  279.                 new Variant(fstCellRowIdx), new Variant(fstCellColIdx))  
  280.                 .toDispatch();  
  281.         Dispatch secCell = Dispatch.call(table, "Cell",  
  282.                 new Variant(secCellRowIdx), new Variant(secCellColIdx))  
  283.                 .toDispatch();  
  284.         Dispatch.call(fstCell, "Merge", secCell);  
  285.     }  
  286.   
  287.     /** 
  288.      * 在指定的单元格里填写数据 
  289.      *  
  290.      * @param tableIndex 
  291.      * @param cellRowIdx 
  292.      * @param cellColIdx 
  293.      * @param txt 
  294.      */  
  295.     public void putTxtToCell(int tableIndex, int cellRowIdx, int cellColIdx,  
  296.             String txt) {  
  297.         // 所有表格  
  298.         Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();  
  299.         // 要填充的表格  
  300.         Dispatch table = Dispatch.call(tables, "Item"new Variant(tableIndex))  
  301.                 .toDispatch();  
  302.         Dispatch cell = Dispatch.call(table, "Cell"new Variant(cellRowIdx),  
  303.                 new Variant(cellColIdx)).toDispatch();  
  304.         Dispatch.call(cell, "Select");  
  305.         Dispatch.put(selection, "Text", txt);         
  306.     }  
  307.       
  308.     /** 
  309.      * 获得指定的单元格里数据 
  310.      *  
  311.      * @param tableIndex 
  312.      * @param cellRowIdx 
  313.      * @param cellColIdx 
  314.      * @return 
  315.      */   
  316.     public String getTxtFromCell(int tableIndex, int cellRowIdx, int cellColIdx) {  
  317.         // 所有表格  
  318.         Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();  
  319.         // 要填充的表格  
  320.         Dispatch table = Dispatch.call(tables, "Item"new Variant(tableIndex))  
  321.                 .toDispatch();  
  322.         Dispatch cell = Dispatch.call(table, "Cell"new Variant(cellRowIdx),  
  323.                 new Variant(cellColIdx)).toDispatch();  
  324.         Dispatch.call(cell, "Select");    
  325.         String ret = "";      
  326.         ret = Dispatch.get(selection, "Text").toString();  
  327.         ret = ret.substring(0, ret.length()-1); //去掉最后的回车符;  
  328.         return ret;  
  329.     }  
  330.   
  331.     /** 
  332.      * 在当前文档拷贝剪贴板数据 
  333.      * @param pos 
  334.      */  
  335.     public void pasteExcelSheet(String pos) {  
  336.         moveStart();  
  337.         if (this.find(pos)) {  
  338.             Dispatch textRange = Dispatch.get(selection, "Range").toDispatch();  
  339.             Dispatch.call(textRange, "Paste");  
  340.         }  
  341.     }  
  342.   
  343.     /** 
  344.      * 在当前文档指定的位置拷贝表格 
  345.      *  
  346.      * @param pos 
  347.      *            当前文档指定的位置 
  348.      * @param tableIndex 
  349.      *            被拷贝的表格在word文档中所处的位置 
  350.      */  
  351.     public void copyTable(String pos, int tableIndex) {  
  352.         // 所有表格  
  353.         Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();  
  354.         // 要填充的表格  
  355.         Dispatch table = Dispatch.call(tables, "Item"new Variant(tableIndex))  
  356.                 .toDispatch();  
  357.         Dispatch range = Dispatch.get(table, "Range").toDispatch();  
  358.         Dispatch.call(range, "Copy");  
  359.         if (this.find(pos)) {  
  360.             Dispatch textRange = Dispatch.get(selection, "Range").toDispatch();  
  361.             Dispatch.call(textRange, "Paste");  
  362.         }  
  363.     }  
  364.   
  365.     /** 
  366.      * 在当前文档指定的位置拷贝来自另一个文档中的表格 
  367.      *  
  368.      * @param anotherDocPath 
  369.      *            另一个文档的磁盘路径 
  370.      * @param tableIndex 
  371.      *            被拷贝的表格在另一格文档中的位置 
  372.      * @param pos 
  373.      *            当前文档指定的位置 
  374.      */  
  375.     public void copyTableFromAnotherDoc(String anotherDocPath, int tableIndex,  
  376.             String pos) {  
  377.         Dispatch doc2 = null;  
  378.         try {  
  379.             doc2 = Dispatch.call(documents, "Open", anotherDocPath)  
  380.                     .toDispatch();  
  381.             // 所有表格  
  382.             Dispatch tables = Dispatch.get(doc2, "Tables").toDispatch();  
  383.             // 要填充的表格  
  384.             Dispatch table = Dispatch.call(tables, "Item",  
  385.                     new Variant(tableIndex)).toDispatch();  
  386.             Dispatch range = Dispatch.get(table, "Range").toDispatch();  
  387.             Dispatch.call(range, "Copy");  
  388.             if (this.find(pos)) {  
  389.                 Dispatch textRange = Dispatch.get(selection, "Range")  
  390.                         .toDispatch();  
  391.                 Dispatch.call(textRange, "Paste");  
  392.             }  
  393.         } catch (Exception e) {  
  394.             e.printStackTrace();  
  395.         } finally {  
  396.             if (doc2 != null) {  
  397.                 Dispatch.call(doc2, "Close"new Variant(saveOnExit));  
  398.                 doc2 = null;  
  399.             }  
  400.         }  
  401.     }  
  402.   
  403.     /** 
  404.      * 在当前文档指定的位置拷贝来自另一个文档中的图片 
  405.      *  
  406.      * @param anotherDocPath 另一个文档的磁盘路径 
  407.      * @param shapeIndex 被拷贝的图片在另一格文档中的位置 
  408.      * @param pos 当前文档指定的位置 
  409.      */  
  410.     public void copyImageFromAnotherDoc(String anotherDocPath, int shapeIndex,  
  411.             String pos) {  
  412.         Dispatch doc2 = null;  
  413.         try {  
  414.             doc2 = Dispatch.call(documents, "Open", anotherDocPath)  
  415.                     .toDispatch();  
  416.             Dispatch shapes = Dispatch.get(doc2, "InLineShapes").toDispatch();  
  417.             Dispatch shape = Dispatch.call(shapes, "Item",  
  418.                     new Variant(shapeIndex)).toDispatch();  
  419.             Dispatch imageRange = Dispatch.get(shape, "Range").toDispatch();  
  420.             Dispatch.call(imageRange, "Copy");  
  421.             if (this.find(pos)) {  
  422.                 Dispatch textRange = Dispatch.get(selection, "Range")  
  423.                         .toDispatch();  
  424.                 Dispatch.call(textRange, "Paste");  
  425.             }  
  426.         } catch (Exception e) {  
  427.             e.printStackTrace();  
  428.         } finally {  
  429.             if (doc2 != null) {  
  430.                 Dispatch.call(doc2, "Close"new Variant(saveOnExit));  
  431.                 doc2 = null;  
  432.             }  
  433.         }  
  434.     }  
  435.   
  436.     /** 
  437.      * 创建表格 
  438.      *  
  439.      * @param pos 
  440.      *            位置 
  441.      * @param cols 
  442.      *            列数 
  443.      * @param rows 
  444.      *            行数 
  445.      */  
  446.     public void createTable(String pos, int numCols, int numRows) {  
  447.         if (find(pos)) {  
  448.             Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();  
  449.             Dispatch range = Dispatch.get(selection, "Range").toDispatch();  
  450.             @SuppressWarnings("unused")  
  451.             Dispatch newTable = Dispatch.call(tables, "Add", range,  
  452.                     new Variant(numRows), new Variant(numCols)).toDispatch();  
  453.             Dispatch.call(selection, "MoveRight");  
  454.         } else {  
  455.             Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();  
  456.             Dispatch range = Dispatch.get(selection, "Range").toDispatch();  
  457.             @SuppressWarnings("unused")  
  458.             Dispatch newTable = Dispatch.call(tables, "Add", range,  
  459.                     new Variant(numRows), new Variant(numCols)).toDispatch();  
  460.             Dispatch.call(selection, "MoveRight");  
  461.         }  
  462.     }  
  463.   
  464.     /** 
  465.      * 在指定行前面增加行 
  466.      *  
  467.      * @param tableIndex 
  468.      *            word文件中的第N张表(从1开始) 
  469.      * @param rowIndex 
  470.      *            指定行的序号(从1开始) 
  471.      */  
  472.     public void addTableRow(int tableIndex, int rowIndex) {  
  473.         // 所有表格  
  474.         Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();  
  475.         // 要填充的表格  
  476.         Dispatch table = Dispatch.call(tables, "Item"new Variant(tableIndex))  
  477.                 .toDispatch();  
  478.         // 表格的所有行  
  479.         Dispatch rows = Dispatch.get(table, "Rows").toDispatch();  
  480.         Dispatch row = Dispatch.call(rows, "Item"new Variant(rowIndex))  
  481.                 .toDispatch();  
  482.         Dispatch.call(rows, "Add"new Variant(row));  
  483.     }  
  484.   
  485.     /** 
  486.      * 在第1行前增加一行 
  487.      *  
  488.      * @param tableIndex 
  489.      *  word文档中的第N张表(从1开始) 
  490.      */  
  491.     public void addFirstTableRow(int tableIndex) {  
  492.         // 所有表格  
  493.         Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();  
  494.         // 要填充的表格  
  495.         Dispatch table = Dispatch.call(tables, "Item"new Variant(tableIndex))  
  496.                 .toDispatch();  
  497.         // 表格的所有行  
  498.         Dispatch rows = Dispatch.get(table, "Rows").toDispatch();  
  499.         Dispatch row = Dispatch.get(rows, "First").toDispatch();  
  500.         Dispatch.call(rows, "Add"new Variant(row));  
  501.     }  
  502.   
  503.     /** 
  504.      * 在最后1行前增加一行 
  505.      *  
  506.      * @param tableIndex 
  507.      *            word文档中的第N张表(从1开始) 
  508.      */  
  509.     public void addLastTableRow(int tableIndex) {  
  510.         // 所有表格  
  511.         Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();  
  512.         // 要填充的表格  
  513.         Dispatch table = Dispatch.call(tables, "Item"new Variant(tableIndex))  
  514.                 .toDispatch();  
  515.         // 表格的所有行  
  516.         Dispatch rows = Dispatch.get(table, "Rows").toDispatch();  
  517.         Dispatch row = Dispatch.get(rows, "Last").toDispatch();  
  518.         Dispatch.call(rows, "Add"new Variant(row));  
  519.     }  
  520.   
  521.     /** 
  522.      * 增加一行 
  523.      *  
  524.      * @param tableIndex 
  525.      *            word文档中的第N张表(从1开始) 
  526.      */  
  527.     public void addRow(int tableIndex) {  
  528.         Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();  
  529.         // 要填充的表格  
  530.         Dispatch table = Dispatch.call(tables, "Item"new Variant(tableIndex))  
  531.                 .toDispatch();  
  532.         // 表格的所有行  
  533.         Dispatch rows = Dispatch.get(table, "Rows").toDispatch();  
  534.         Dispatch.call(rows, "Add");  
  535.     }  
  536.   
  537.     /** 
  538.      * 增加一列 
  539.      *  
  540.      * @param tableIndex 
  541.      *            word文档中的第N张表(从1开始) 
  542.      */  
  543.     public void addCol(int tableIndex) {  
  544.         // 所有表格  
  545.         Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();  
  546.         // 要填充的表格  
  547.         Dispatch table = Dispatch.call(tables, "Item"new Variant(tableIndex))  
  548.                 .toDispatch();  
  549.         // 表格的所有行  
  550.         Dispatch cols = Dispatch.get(table, "Columns").toDispatch();  
  551.         Dispatch.call(cols, "Add").toDispatch();  
  552.         Dispatch.call(cols, "AutoFit");  
  553.     }  
  554.   
  555.     /** 
  556.      * 在指定列前面增加表格的列 
  557.      *  
  558.      * @param tableIndex 
  559.      *            word文档中的第N张表(从1开始) 
  560.      * @param colIndex 
  561.      *            制定列的序号 (从1开始) 
  562.      */  
  563.     public void addTableCol(int tableIndex, int colIndex) {  
  564.         // 所有表格  
  565.         Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();  
  566.         // 要填充的表格  
  567.         Dispatch table = Dispatch.call(tables, "Item"new Variant(tableIndex))  
  568.                 .toDispatch();  
  569.         // 表格的所有行  
  570.         Dispatch cols = Dispatch.get(table, "Columns").toDispatch();  
  571.         System.out.println(Dispatch.get(cols, "Count"));  
  572.         Dispatch col = Dispatch.call(cols, "Item"new Variant(colIndex))  
  573.                 .toDispatch();  
  574.         // Dispatch col = Dispatch.get(cols, "First").toDispatch();  
  575.         Dispatch.call(cols, "Add", col).toDispatch();  
  576.         Dispatch.call(cols, "AutoFit");  
  577.     }  
  578.   
  579.     /** 
  580.      * 在第1列前增加一列 
  581.      *  
  582.      * @param tableIndex 
  583.      *            word文档中的第N张表(从1开始) 
  584.      */  
  585.     public void addFirstTableCol(int tableIndex) {  
  586.         Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();  
  587.         // 要填充的表格  
  588.         Dispatch table = Dispatch.call(tables, "Item"new Variant(tableIndex))  
  589.                 .toDispatch();  
  590.         // 表格的所有行  
  591.         Dispatch cols = Dispatch.get(table, "Columns").toDispatch();  
  592.         Dispatch col = Dispatch.get(cols, "First").toDispatch();  
  593.         Dispatch.call(cols, "Add", col).toDispatch();  
  594.         Dispatch.call(cols, "AutoFit");  
  595.     }  
  596.   
  597.     /** 
  598.      * 在最后一列前增加一列 
  599.      *  
  600.      * @param tableIndex 
  601.      *            word文档中的第N张表(从1开始) 
  602.      */  
  603.     public void addLastTableCol(int tableIndex) {  
  604.         Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();  
  605.         // 要填充的表格  
  606.         Dispatch table = Dispatch.call(tables, "Item"new Variant(tableIndex))  
  607.                 .toDispatch();  
  608.         // 表格的所有行  
  609.         Dispatch cols = Dispatch.get(table, "Columns").toDispatch();  
  610.         Dispatch col = Dispatch.get(cols, "Last").toDispatch();  
  611.         Dispatch.call(cols, "Add", col).toDispatch();  
  612.         Dispatch.call(cols, "AutoFit");  
  613.     }  
  614.   
  615.     /** 
  616.      * 自动调整表格 
  617.      * 
  618.      */  
  619.     @SuppressWarnings("deprecation")  
  620.     public void autoFitTable() {  
  621.         Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();  
  622.         int count = Dispatch.get(tables, "Count").toInt();  
  623.         for (int i = 0; i < count; i++) {  
  624.             Dispatch table = Dispatch.call(tables, "Item"new Variant(i + 1))  
  625.                     .toDispatch();  
  626.             Dispatch cols = Dispatch.get(table, "Columns").toDispatch();  
  627.             Dispatch.call(cols, "AutoFit");  
  628.         }  
  629.     }  
  630.   
  631.     /** 
  632.      * 调用word里的宏以调整表格的宽度,其中宏保存在document下 
  633.      * 
  634.      */  
  635.     @SuppressWarnings("deprecation")  
  636.     public void callWordMacro() {  
  637.         Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();  
  638.         int count = Dispatch.get(tables, "Count").toInt();  
  639.         Variant vMacroName = new Variant("Normal.NewMacros.tableFit");  
  640.         @SuppressWarnings("unused")  
  641.         Variant vParam = new Variant("param1");  
  642.         @SuppressWarnings("unused")  
  643.         Variant para[] = new Variant[] { vMacroName };  
  644.         for (int i = 0; i < count; i++) {  
  645.             Dispatch table = Dispatch.call(tables, "Item"new Variant(i + 1))  
  646.                     .toDispatch();  
  647.             Dispatch.call(table, "Select");  
  648.             Dispatch.call(word, "Run""tableFitContent");  
  649.         }  
  650.     }  
  651.   
  652.     /** 
  653.      * 设置当前选定内容的字体 
  654.      *  
  655.      * @param boldSize 
  656.      * @param italicSize 
  657.      * @param underLineSize 
  658.      *            下划线 
  659.      * @param colorSize 
  660.      *            字体颜色 
  661.      * @param size 
  662.      *            字体大小 
  663.      * @param name 
  664.      *            字体名称 
  665.      */  
  666.     public void setFont(boolean bold, boolean italic, boolean underLine,  
  667.             String colorSize, String size, String name) {  
  668.         Dispatch font = Dispatch.get(selection, "Font").toDispatch();  
  669.         Dispatch.put(font, "Name"new Variant(name));  
  670.         Dispatch.put(font, "Bold"new Variant(bold));  
  671.         Dispatch.put(font, "Italic"new Variant(italic));  
  672.         Dispatch.put(font, "Underline"new Variant(underLine));  
  673.         Dispatch.put(font, "Color", colorSize);  
  674.         Dispatch.put(font, "Size", size);  
  675.     }  
  676.       
  677.     /** 
  678.      * 设置单元格被选中 
  679.      *  
  680.      * @param tableIndex 
  681.      * @param cellRowIdx 
  682.      * @param cellColIdx 
  683.      */  
  684.     public void setTableCellSelected(int tableIndex, int cellRowIdx, int cellColIdx){  
  685.         Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();  
  686.         Dispatch table = Dispatch.call(tables, "Item"new Variant(tableIndex))  
  687.                 .toDispatch();  
  688.         Dispatch cell = Dispatch.call(table, "Cell"new Variant(cellRowIdx),  
  689.                 new Variant(cellColIdx)).toDispatch();  
  690.         Dispatch.call(cell, "Select");  
  691.     }  
  692.       
  693.     /** 
  694.      * 设置选定单元格的垂直对起方式, 请使用setTableCellSelected选中一个单元格 
  695.      * @param align 0-顶端, 1-居中, 3-底端 
  696.      */  
  697.     public void setCellVerticalAlign(int verticalAlign){  
  698.         Dispatch cells = Dispatch.get(selection, "Cells").toDispatch();       
  699.         Dispatch.put(cells, "VerticalAlignment"new Variant(verticalAlign));         
  700.     }  
  701.       
  702.     /** 
  703.      * 设置当前文档中所有表格水平居中方式及其它一些格式,用在将word文件转化为html中,针对申报表 
  704.      */  
  705.     @SuppressWarnings("deprecation")  
  706.     public void setApplyTableFormat(){  
  707.         Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();  
  708.         int tabCount = Integer.valueOf(Dispatch.get(tables, "Count").toString());   //System.out.println(tabCount);  
  709.         System.out.println("*******************************************************");  
  710.         for(int i=1; i<=tabCount; i++){        
  711.             Dispatch table = Dispatch.call(tables, "Item"new Variant(i)).toDispatch();  
  712.             Dispatch rows = Dispatch.get(table, "Rows").toDispatch();  
  713.               
  714.             if(i==1){  
  715.                 Dispatch.put(rows, "Alignment"new Variant(2));    //1-居中,2-Right  
  716.                 continue ;  
  717.             }  
  718.             Dispatch.put(rows, "Alignment"new Variant(1));    //1-居中            
  719.             Dispatch.call(table, "AutoFitBehavior"new Variant(1));//设置自动调整表格方式,1-根据窗口自动调整  
  720.             Dispatch.put(table, "PreferredWidthType"new Variant(1));  
  721.             Dispatch.put(table, "PreferredWidth"new Variant(700));              
  722.             System.out.println(Dispatch.get(rows, "HeightRule").toString());  
  723.             Dispatch.put(rows, "HeightRule"new Variant(1));   //0-自动wdRowHeightAuto,1-最小值wdRowHeightAtLeast, 2-固定wdRowHeightExactly     
  724.             Dispatch.put(rows, "Height"new Variant(0.04*28.35));            
  725.             //int oldAlign = Integer.valueOf(Dispatch.get(rows, "Alignment").toString());     
  726.             //System.out.println("Algin:" + oldAlign);  
  727.         }     
  728.     }  
  729.       
  730.     /** 
  731.      * 设置段落格式 
  732.      *  
  733.      * @param alignment  
  734.      *          0-左对齐, 1-右对齐, 2-右对齐, 3-两端对齐, 4-分散对齐 
  735.      * @param lineSpaceingRule    
  736.      * @param lineUnitBefore      
  737.      * @param lineUnitAfter   
  738.      * @param characterUnitFirstLineIndent 
  739.      */  
  740.     public void setParagraphsProperties(int alignment, int lineSpaceingRule,  
  741.             int lineUnitBefore, int lineUnitAfter, int characterUnitFirstLineIndent){  
  742.         Dispatch paragraphs = Dispatch.get(selection, "Paragraphs").toDispatch();     
  743.         Dispatch.put(paragraphs, "Alignment"new Variant(alignment));              //对齐方式            
  744.         Dispatch.put(paragraphs, "LineSpacingRule"new Variant(lineSpaceingRule)); //行距  
  745.         Dispatch.put(paragraphs, "LineUnitBefore"new Variant(lineUnitBefore));    //段前  
  746.         Dispatch.put(paragraphs, "LineUnitAfter"new Variant(lineUnitAfter));      //段后      
  747.         Dispatch.put(paragraphs, "CharacterUnitFirstLineIndent",   
  748.                 new Variant(characterUnitFirstLineIndent));                         //首行缩进字符数  
  749.     }     
  750.       
  751.     /** 
  752.      * 设置当前段落格式, 使用前,请先选中段落 
  753.      */  
  754.     public void getParagraphsProperties(){  
  755.         Dispatch paragraphs = Dispatch.get(selection, "Paragraphs").toDispatch();         
  756.         String val = Dispatch.get(paragraphs, "LineSpacingRule").toString();    //行距  
  757.         val = Dispatch.get(paragraphs, "Alignment").toString();         //对齐方式    
  758.         val = Dispatch.get(paragraphs, "LineUnitBefore").toString();    //段前行数  
  759.         val = Dispatch.get(paragraphs, "LineUnitAfter").toString();     //段后行数  
  760.         val = Dispatch.get(paragraphs, "FirstLineIndent").toString();   //首行缩进  
  761.         val = Dispatch.get(paragraphs, "CharacterUnitFirstLineIndent").toString();  //首行缩进字符数  
  762.     }  
  763.   
  764.     /** 
  765.      * 文件保存或另存为 
  766.      *  
  767.      * @param savePath 
  768.      *            保存或另存为路径 
  769.      */  
  770.     public void save(String savePath) {  
  771.         Dispatch.call(Dispatch.call(word, "WordBasic").getDispatch(),  
  772.                 "FileSaveAs", savePath);  
  773.     }     
  774.       
  775.     /** 
  776.      * 文件保存为html格式 
  777.      *  
  778.      * @param savePath 
  779.      * @param htmlPath 
  780.      */  
  781.     public void saveAsHtml(String htmlPath){  
  782.         Dispatch.invoke(doc,"SaveAs", Dispatch.Method,   
  783.                 new Object[]{htmlPath, new Variant(8)}, new int[1]);   
  784.     }  
  785.   
  786.     /** 
  787.      * 关闭文档 
  788.      *@param val 0不保存修改 -1 保存修改 -2 提示是否保存修改 
  789.      */  
  790.     public void closeDocument(int val) {  
  791.         Dispatch.call(doc, "Close"new Variant(val));  
  792.         doc = null;  
  793.     }  
  794.   
  795.     /** 
  796.      * 关闭当前word文档 
  797.      *  
  798.      */  
  799.     public void closeDocument() {  
  800.         if (doc != null) {  
  801.             Dispatch.call(doc, "Save");  
  802.             Dispatch.call(doc, "Close"new Variant(saveOnExit));  
  803.             doc = null;  
  804.         }  
  805.     }  
  806.       
  807.     public void closeDocumentWithoutSave(){  
  808.         if (doc != null) {            
  809.             Dispatch.call(doc, "Close"new Variant(false));  
  810.             doc = null;  
  811.         }  
  812.     }  
  813.   
  814.     /** 
  815.      * 关闭全部应用 
  816.      *  
  817.      */  
  818.     public void close() {  
  819.         //closeDocument();  
  820.         if (word != null) {  
  821.             Dispatch.call(word, "Quit");  
  822.             word = null;  
  823.         }  
  824.         selection = null;  
  825.         documents = null;  
  826.     }  
  827.       
  828.     /** 
  829.      * 打印当前word文档 
  830.      *  
  831.      */  
  832.     public void printFile() {  
  833.         if (doc != null) {  
  834.             Dispatch.call(doc, "PrintOut");  
  835.         }  
  836.     }  
  837.       
  838.     /** 
  839.      * 保护当前档,如果不存在, 使用expression.Protect(Type, NoReset, Password) 
  840.      *  
  841.      * @param pwd 
  842.      * WdProtectionType 可以是下列 WdProtectionType 常量之一:  
  843.      *      1-wdAllowOnlyComments, 2-wdAllowOnlyFormFields, 0-wdAllowOnlyRevisions,  
  844.      *      -1-wdNoProtection, 3-wdAllowOnlyReading 
  845.      *  
  846.      * 使用参照 main1() 
  847.      */  
  848.     public void protectedWord(String pwd){  
  849.         String protectionType = Dispatch.get(doc, "ProtectionType").toString();  
  850.         if(protectionType.equals("-1")){      
  851.             Dispatch.call(doc, "Protect"new Variant(3), new Variant(true), pwd);  
  852.         }     
  853.     }  
  854.       
  855.     /** 
  856.      * 解除文档保护,如果存在 
  857.      * @param pwd 
  858.      * WdProtectionType 常量之一(Long 类型,只读): 
  859.      *      1-wdAllowOnlyComments,2-wdAllowOnlyFormFields、 
  860.      *      0-wdAllowOnlyRevisions,-1-wdNoProtection, 3-wdAllowOnlyReading 
  861.      *  
  862.      *      使用参照 main1() 
  863.      */  
  864.     public void unProtectedWord(String pwd){  
  865.         String protectionType = Dispatch.get(doc, "ProtectionType").toString();  
  866.         if(protectionType.equals("3")){   
  867.             Dispatch.call(doc, "Unprotect", pwd);  
  868.         }  
  869.     }  
  870.       
  871.     /** 
  872.      * 设置word文档安全级别 
  873.      * @param value 
  874.      *      1-msoAutomationSecurityByUI  使用“安全”对话框指定的安全设置。 
  875.      *      2-msoAutomationSecurityForceDisable  在程序打开的所有文件中禁用所有宏,而不显示任何安全提醒。 
  876.      *      3-msoAutomationSecurityLow  启用所有宏,这是启动应用程序时的默认值。 
  877.      */  
  878.     public void setAutomationSecurity(int value){  
  879.         word.setProperty("AutomationSecurity"new Variant(value));   
  880.     }  
  881.       
  882.     /** 
  883.      * 读取文档中第paragraphsIndex段文字的内容; 
  884.      * @param paragraphsIndex 
  885.      * @return 
  886.      */  
  887.     public String getParagraphs(int paragraphsIndex){  
  888.         String ret = "";  
  889.         Dispatch paragraphs = Dispatch.get(doc, "Paragraphs").toDispatch(); // 所有段落  
  890.         int paragraphCount = Dispatch.get(paragraphs, "Count").getInt();            // 一共的段落数  
  891.         Dispatch paragraph = null;  
  892.         Dispatch range = null;  
  893.         if(paragraphCount > paragraphsIndex && 0 < paragraphsIndex){    
  894.             paragraph = Dispatch.call(paragraphs, "Item"new Variant(paragraphsIndex)).toDispatch();  
  895.             range = Dispatch.get(paragraph, "Range").toDispatch();  
  896.             ret = Dispatch.get(range, "Text").toString();  
  897.         }     
  898.         return ret;  
  899.     }  
  900.       
  901.     /** 
  902.      * 设置页眉文字 
  903.      * @param cont 
  904.      * @return 
  905.      *  
  906.      * Sub AddHeaderText() 
  907.      * '设置页眉或页脚中的文字 
  908.      * '由 Headers、Footers 和 HeaderFooter 属性返回 HeaderFooter 对象。下列示例更改当前页眉中的文字。 
  909.      *  With ActiveDocument.ActiveWindow.View 
  910.      *      .SeekView = wdSeekCurrentPageHeader 
  911.      *      Selection.HeaderFooter.Range.Text = "Header text" 
  912.      *      .SeekView = wdSeekMainDocument 
  913.      *  End With 
  914.      * End Sub 
  915.      */  
  916.     public void setHeaderContent(String cont){  
  917.         Dispatch activeWindow = Dispatch.get(doc, "ActiveWindow").toDispatch();  
  918.         Dispatch view = Dispatch.get(activeWindow, "View").toDispatch();  
  919.         //Dispatch seekView = Dispatch.get(view, "SeekView").toDispatch();  
  920.         Dispatch.put(view, "SeekView"new Variant(9));         //wdSeekCurrentPageHeader-9  
  921.           
  922.         Dispatch headerFooter = Dispatch.get(selection, "HeaderFooter").toDispatch();  
  923.         Dispatch range = Dispatch.get(headerFooter, "Range").toDispatch();  
  924.         Dispatch.put(range, "Text"new Variant(cont));   
  925.         //String content = Dispatch.get(range, "Text").toString();  
  926.         Dispatch font = Dispatch.get(range, "Font").toDispatch();  
  927.           
  928.         Dispatch.put(font, "Name"new Variant("楷体_GB2312"));  
  929.         Dispatch.put(font, "Bold"new Variant(true));  
  930.         //Dispatch.put(font, "Italic", new Variant(true));  
  931.         //Dispatch.put(font, "Underline", new Variant(true));  
  932.         Dispatch.put(font, "Size"9);  
  933.           
  934.         Dispatch.put(view, "SeekView"new Variant(0));         //wdSeekMainDocument-0恢复视图;  
  935.     }  
  936.       
  937.     public static void main(String[] args)throws Exception{  
  938.         WordBean word = new WordBean();   
  939.         word.openDocument("D:/竞价平台.doc");  
  940.           
  941.         word.setHeaderContent("*****************88设置页眉内容11111111111111111!");  
  942.         //word.unProtectedWord("1qaz");  
  943.         //word.protectedWord("123");  
  944.         System.out.print(word.getParagraphs(3));  
  945.         word.closeDocument();  
  946.         word.close();  
  947.     }  
  948. }  

0 0
原创粉丝点击