java操作复杂的word

/* 
* @(#) WordBean.java Create on 2012-5-17 下午02:58:26  
*  
* Copyright 2012 by xl.  
*/


package cn.tools.word;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComFailException;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;

/**
*
* @author zxd
* @date   2012-5-17
*/
public class WordHelper {



private ActiveXComponent MsWordApp = null;

private static final int MAX_RETRY = 10;//取Com接口异常的最多重试次数.


private Dispatch document = null;

public WordHelper() {
if (MsWordApp == null) {
MsWordApp = new ActiveXComponent("Word.Application");
}
}

public void setVisible(boolean visible) {
MsWordApp.setProperty("Visible", new Variant(visible));
}


public void createNewDocument() {

Dispatch documents = Dispatch.get(MsWordApp, "Documents").toDispatch();

document = Dispatch.call(documents, "Add").toDispatch();
}

public void openFile(String wordFilePath) {
// Find the Documents collection object maintained by Word
// documents表示word的所有文档窗口,(word是多文档应用程序)
Dispatch documents = Dispatch.get(MsWordApp, "Documents").toDispatch();
document = Dispatch.call(documents, "Open", wordFilePath,
new Variant(true)/* 是否进行转换ConfirmConversions */,
new Variant(false)/* 是否只读 */).toDispatch();
}
/**
* 插入数据
* @Title: insertText
* @data:2012-5-18上午11:04:07
* @author:zxd
*
* @param textToInsert
*/
public void insertText(String textToInsert) {
Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch();

Dispatch.put(selection, "Text", textToInsert);
Dispatch.call(selection, "MoveRight", new Variant(1), new Variant(1));
}
/**
* 插入图片
* @Title: insertJpeg
* @data:2012-5-17下午03:11:22
* @author:zxd
*
* @param jpegFilePath
*/
public void insertJpeg(String jpegFilePath){
Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch();
Dispatch image = Dispatch.get(selection, "InLineShapes").toDispatch();
Dispatch.call(image, "AddPicture", jpegFilePath);
}



    public void insertFormatContent(String text) { 
        Dispatch wordContent = Dispatch.get(document, "Content").toDispatch(); // 取得word文件的内容 
        Dispatch.call(wordContent, "InsertAfter", text);// 插入一个段落到最后 
        Dispatch paragraphs = Dispatch.get(wordContent, "Paragraphs") 
                .toDispatch(); // 所有段落 
        int paragraphCount = Dispatch.get(paragraphs, "Count").changeType( 
                Variant.VariantInt).getInt();// 一共的段落数 
        // 找到刚输入的段落,设置格式 
        Dispatch lastParagraph = Dispatch.call(paragraphs, "Item", 
                new Variant(paragraphCount)).toDispatch(); // 最后一段(也就是刚插入的) 
        // Range 对象表示文档中的一个连续范围,由一个起始字符位置和一个终止字符位置定义 
        Dispatch lastParagraphRange = Dispatch.get(lastParagraph, "Range") 
                .toDispatch(); 
        Dispatch font = Dispatch.get(lastParagraphRange, "Font").toDispatch(); 
        Dispatch.put(font, "Bold", new Variant(false)); // 设置为黑体 
        Dispatch.put(font, "Italic", new Variant(true)); // 设置为斜体 
        Dispatch.put(font, "Name", new Variant("宋体")); // 
        Dispatch.put(font, "Size", new Variant(9)); // 小四 
        Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch(); 
        Dispatch.call(selection, "TypeParagraph");// 插入一个空行 
        Dispatch alignment = Dispatch.get(selection, "ParagraphFormat") 
                .toDispatch();// 段落格式 
        Dispatch.put(alignment, "Alignment", "3"); // (1:置中 2:靠右 3:靠左) 
    }
  
    public void listIndent(
            final int pos) {
Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch();
        Dispatch range = Dispatch.get(selection, "Range").toDispatch();
        Dispatch listFormat = Dispatch.get(range, "ListFormat").toDispatch();
        for (int i = 0; i < pos; i++) {
            Dispatch.call(listFormat, "ListIndent");
        }
    }
   /**
    * 插入一个换耶夫
    * @Title: insertPageBreak
    * @data:2012-7-5下午03:46:01
    * @author:zxd
    *
    */
   public void insertPageBreak() {
  
   Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch();
       Dispatch.call(selection, "InsertBreak", new Variant(2));
   }
   /**
    * 插入一段文字.
    * @param textToInsert 文字
    * @param style 样式
    */
   public void insertText(
           final String textToInsert,
           final String style) {
   Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch();
       Dispatch.put(selection, "Text", textToInsert);
       Dispatch.put(selection, "Style", getOutlineStyle(style));
       Dispatch.call(selection, "MoveRight");
   }

   public Variant getOutlineStyle(
           final String style) {

       int index = 1;
       while (true) {
           try {
               return Dispatch.call(
                       Dispatch.get(document, "Styles").toDispatch(),
                       "Item", new Variant(style));
           } catch (ComFailException e) {
               if (index++ >= MAX_RETRY) {
                   throw e;
               } else {
                   continue;
               }
           }
       }
   }




    public void insertFormatStr(String text) { 
Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch();
Dispatch.put(selection, "Text", text);
        Dispatch font = Dispatch.get(selection, "Font").toDispatch(); 
        Dispatch.put(font, "Bold", new Variant(true)); // 设置为黑体 
        Dispatch.put(font, "Italic", new Variant(false)); // 设置为斜体 
        Dispatch.put(font, "Name", new Variant("楷体_GB2312")); // 
        Dispatch.put(font, "Size", new Variant(12)); // 小四 
    } 
/**
* 插入表格内容
* @Title: insertTable
* @data:2012-5-18上午11:05:50
* @author:zxd
*
* @param tableTitle
* @param row
* @param column
*/
// word 中在对表格进行遍历的时候 ,是先列后行 先column 后cell
// 另外下标从1开始
public void createTable(String pos, int numCols, int numRows) {
Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch();
  if (find(pos)) {
   Dispatch tables = Dispatch.get(document, "Tables").toDispatch();
   Dispatch range = Dispatch.get(selection, "Range").toDispatch();
   Dispatch newTable = Dispatch.call(tables, "Add", range,
     new Variant(numRows), new Variant(numCols)).toDispatch();
   Dispatch.call(selection, "Right");
  }else{
    Dispatch tables = Dispatch.get(document, "Tables").toDispatch();
    Dispatch range = Dispatch.get(selection, "Range").toDispatch();
    Dispatch newTable = Dispatch.call(tables, "Add", range,
      new Variant(numRows), new Variant(numCols)).toDispatch();
    Dispatch.call(selection, "MoveRight");
  }
}

/**
* 在指定单元格中填写数据
* @Title: putTxtToCell
* @data:2012-5-17下午04:39:38
* @author:zxd
*
* @param table
* @param cellRowIdx
* @param CellColIdx
* @param text
*/
public void putTxtToCell(Dispatch table,int cellRowIdx,int CellColIdx,String text){
Dispatch cell = Dispatch.call(table, "Cell",new Variant(cellRowIdx), new Variant(CellColIdx)).toDispatch();
Dispatch.call(cell, "Select");
Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch();
Dispatch.put(selection, "Text", text);//往里面写入数据
}
/**
* 在指定单元格里面填写数据
* @Title: putTxtToCell
* @data:2012-5-17下午05:22:16
* @author:zxd
*
* @param tableIndex
* @param cellRowIdx
* @param cellColIdx
* @param txt
*/
public void putTxtToCell(int tableIndex, int cellRowIdx, int cellColIdx,
String txt){
//获取所有表格
Dispatch tables = Dispatch.get(document, "Tables").toDispatch();
//要填充的表格
Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex))
.toDispatch();
//要填充的单元格
Dispatch cell = Dispatch.call(table, "Cell", new Variant(cellRowIdx),
new Variant(cellColIdx)).toDispatch();
Dispatch.call(cell, "Select");
Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch();
Dispatch.put(selection, "text", txt);
}
/**
* 往单元格里面填充图片
* @Title: putTxtToImg
* @data:2012-6-29下午03:51:34
* @author:zxd
*
* @param tableIndex
* @param cellRowIdx
* @param cellColIdx
* @param txt
*/
public void putTxtToImg(int tableIndex,int cellRowIdx,int cellColIdx,String jpegFilePath){
//获取所有表格
Dispatch tables = Dispatch.get(document, "Tables").toDispatch();
//要填充的表格
Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex))
.toDispatch();
//要填充的单元格
Dispatch cell = Dispatch.call(table, "Cell", new Variant(cellRowIdx),
new Variant(cellColIdx)).toDispatch();
Dispatch.call(cell, "Select");
Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch();
Dispatch image = Dispatch.get(selection, "InLineShapes").toDispatch();
Dispatch.call(image, "AddPicture", jpegFilePath);


}
/**
* 合并连个单元格
* @Title: mergeCell
* @data:2012-5-18上午10:15:17
* @author:zxd
*
* @param cell1
* @param cell2
*/
public void mergeCell(Dispatch cell1, Dispatch cell2){
Dispatch.call(cell1, "Merge",cell2);
}
/**
* 合并两个单元格
* @Title: mergeCell
* @data:2012-5-18上午10:17:03
* @author:zxd
*
* @param table
* @param row1
* @param col1
* @param row2
* @param col2
*/
public void mergeCell(int tableIndex, int fstCellRowIdx, int fstCellColIdx,
   int secCellRowIdx, int secCellColIdx) {
  // 所有表格
  Dispatch tables = Dispatch.get(document, "Tables").toDispatch();
  // 要填充的表格
  Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex))
    .toDispatch();
  Dispatch fstCell = Dispatch.call(table, "Cell",
    new Variant(fstCellRowIdx), new Variant(fstCellColIdx))
    .toDispatch();
  Dispatch secCell = Dispatch.call(table, "Cell",
    new Variant(secCellRowIdx), new Variant(secCellColIdx))
    .toDispatch();
  Dispatch.call(fstCell, "Merge", secCell);
}


// ========================================================
/** */
/**
* 把选定的内容或光标插入点向上移动
*
* @param pos
*            移动的距离
*/
public void moveUp(int pos){
Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch();
for (int i = 0; i < pos; i++) {
Dispatch.call(selection, "MoveUp");
}
}
/**
* 向下移动
* @Title: moveDown
* @data:2012-6-29下午02:56:14
* @author:zxd
*
* @param pos
*/
public void moveDown(int pos){
Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch();
for (int i = 0; i < pos; i++) {
Dispatch.call(selection, "MoveDown");
}

}
public void moveRight(int pos){
Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch();
for (int i = 0; i < pos; i++) {
Dispatch.call(selection, "MoveRight");
}
}
/**
* 查找文本
* @Title: find
* @data:2012-5-18上午10:28:44
* @author:zxd
*
* @param toFindText
* @return
*/
public boolean find(String toFindText){
if (toFindText == null || toFindText.equals(""))
return false;
Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch(); // 输入内容需要的对象
// 从selection所在位置开始查询
Dispatch find = Dispatch.call(selection, "Find").toDispatch();
// 设置要查找的内容
Dispatch.put(find, "Text", toFindText);
// 向前查找
Dispatch.put(find, "MatchWholeWord", "True");
// 查找并选中
return Dispatch.call(find, "Execute").getBoolean();
}
/**
* 把选 定的内容设为替换的内容
* @Title: replaceText
* @data:2012-5-18上午10:29:37
* @author:zxd
*
* @param toFindText
* @param newText
* @return
*/
public boolean replaceText(String toFindText, String newText){
if(!find(toFindText)){
return false;
}
else{
Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch();//输入内容的对象
Dispatch.put(selection, "Text", newText);
return true;
}
}
/**
* 保存文档内容
* @Title: save
* @data:2012-5-18上午10:32:55
* @author:zxd
*
*/
public void save() {
Dispatch.get(document, "Save");
}
/**
* 保存文件
* @Title: saveFiles
* @data:2012-5-18上午10:34:04
* @author:zxd
*
* @param filename
*/
public void saveFiles(String filename){
Dispatch.call(document, "Save");
}
/**
* 另存为
* @Title: saveFilesAs
* @data:2012-5-18上午10:38:00
* @author:zxd
*
* @param filename
*/
public void saveFilesAs(String filename){
Dispatch.call(document, "SaveAs",filename);
}
/**
* 关闭文件
* @Title: closeDocument
* @data:2012-5-18上午10:40:45
* @author:zxd
*
*/
public void closeDocument(){
Dispatch.call(document, "Close",new Variant(0));
}
/**
* 关闭word
* @Title: closeWord
* @data:2012-5-18上午10:42:10
* @author:zxd
*
*/
public void closeWord(){
Dispatch.call(MsWordApp, "Quit");
MsWordApp = null;
document = null;

}
/**
* 设置word打开后的位置
* @Title: setLocation
* @data:2012-5-18上午10:43:04
* @author:zxd
*
*/
public void setLocation(){
Dispatch actWindow = Dispatch.get(MsWordApp, "Application").toDispatch();//得到当前位置
Dispatch.put(actWindow, "WindowState", new Variant(1));
// 1=maximize
// 2=minimize
Dispatch.put(actWindow, "Top", new Variant(0));
Dispatch.put(actWindow, "Left", new Variant(0));
Dispatch.put(actWindow, "Height", new Variant(600));
Dispatch.put(actWindow, "width", new Variant(800));

}

public void setSeekView(String seekView) {
Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch(); // 输入内容需要的对象
if(seekView != null && !"".equals(seekView)){
//取得活动窗体对象  
Dispatch   ActiveWindow = MsWordApp.getProperty("ActiveWindow").toDispatch();  
//取得活动窗格对象  
Dispatch   ActivePane = Dispatch.get(ActiveWindow,"ActivePane").toDispatch();  
//取得视窗对象  
Dispatch   View  = Dispatch.get(ActivePane, "View").toDispatch();  
try{     
Dispatch.put(View,"SeekView", "9"); //设置页眉 
Dispatch.call(selection, "TypeParagraph");
Dispatch alignment = Dispatch.get(selection, "ParagraphFormat")
.toDispatch();// 段落格式
Dispatch.put(alignment, "Alignment", 2); // (1:置中 2:靠右 3:靠左)
moveDown(1);
Dispatch.put(selection,"Text",seekView);
Dispatch font = Dispatch.get(selection, "Font").toDispatch();
Dispatch.put(font,"Size", new Variant(9));
Dispatch.call(selection,"MoveRight",new Variant(1),new Variant(1));
Dispatch.put(View, "SeekView", "10"); // 10是设置页脚
}finally{
if(ActiveWindow != null ) ActiveWindow.safeRelease();
if(ActivePane != null ) ActivePane.safeRelease();
if(View != null ) View.safeRelease();
}

}
}

public String theOtherFindText(String value){
//shapes集合
Dispatch shapes = Dispatch.get(document, "Shapes").toDispatch();
//shape的个数
String Count=Dispatch.get(shapes, "Count").toString();
int counts=Integer.parseInt(Count);
for(int i=1;i<=counts;i++){ //Item 下标从1 开始
//取得一个shape
Dispatch shape=Dispatch.call(shapes, "Item",new Variant(i)).toDispatch(); 
Dispatch textframe=Dispatch.get(shape, "TextFrame").toDispatch();

boolean hasText=Dispatch.call(textframe, "HasText").toBoolean();
if(hasText){
Dispatch TextRange=Dispatch.get(textframe, "TextRange").toDispatch();
String str=Dispatch.get(TextRange, "Text").toString();
Dispatch.put(TextRange, "Text",value); //替换内容
}
}
return "";
}
/**
* 将文件移动到首位置
* @Title: moveStart
* @data:2012-6-29上午11:51:25
* @author:zxd
*
*/
public void moveStart() {
Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch(); // 输入内容需要的对象
  if (selection == null)
   selection = Dispatch.get(MsWordApp, "Selection").toDispatch();
  Dispatch.call(selection, "HomeKey", new Variant(6));
}

/**
* 查找文本,并且替换
* @Title: replaceAllText
* @data:2012-6-29下午02:51:18
* @author:zxd
*
* @param toFindText
* @param newText
*/
public void replaceAllText(String toFindText, String newText) {

Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch(); // 输入内容需要的对象
  while (find(toFindText)) {
   Dispatch.put(selection, "Text", newText);
   Dispatch.call(selection, "MoveRight");
  }
}

  public void insertToc()
  {
Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch(); // 输入内容需要的对象
Dispatch range = Dispatch.get(selection, "RANGE").toDispatch();
Dispatch fields = Dispatch.call(selection, "FIELDS").toDispatch(); 
Dispatch.call(fields,"ADD",range,new Variant(-1), new Variant("TOC \\h "), new Variant(false));
  }
/**
* 回车换行
* @Title: enter
* @data:2012-7-2上午10:45:36
* @author:zxd
*
*/
  public void enter() {
Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch(); // 输入内容需要的对象
        int index = 1;
        while (true) {
            try {
                Dispatch.call(selection,"TypeParagraph");
                break;
            } catch (ComFailException e) {
                if (index++ >= MAX_RETRY) {
                    throw e;
                } else {
                    continue;
                }
            }
        }
    }

  public void insertHylinks(String pageUrl){
  Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch(); // 输入内容需要的对象
  Dispatch Hyperlinks = Dispatch.get(document,"Hyperlinks").toDispatch();
  Dispatch range = Dispatch.get(selection, "Range").toDispatch();
  Dispatch h=Dispatch.invoke(
  Hyperlinks,"Add", Dispatch.Method,
  new Object[]{ range,new Variant(pageUrl)},new int[1]).toDispatch();
  Dispatch hRange=Dispatch.get(h, "Range").toDispatch();
  Dispatch.call(hRange,"select");
  Dispatch.call(selection,"MoveRight",new Variant(1),new Variant(1));
  }
  /**
   * 光标移到末尾
   * @Title: moveEnd
   * @data:2012-7-5下午05:32:14
   * @author:zxd
   *
   */
    public void moveEnd() {
Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch(); // 输入内容需要的对象
        if (selection == null) {
            selection = Dispatch.get(MsWordApp, "Selection").toDispatch();
        }

        Dispatch.call(selection, "EndKey", new Variant(6));
    }



}

猜你喜欢

转载自sansan521.iteye.com/blog/1591335