• jacob操作word (转)


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