Java操作Word文档封装类

来源:互联网 发布:本地端口怎么开启 编辑:程序博客网 时间:2024/05/17 01:52

importjava.io.File;
 
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComFailException;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
 
final class WordBean {
    /**
     *
读取Com接口异常的最多重试次数.
     */
    private static final int MAX_RETRY = 10;
    /**
     * word
文档.
     */
    private Dispatch doc;
    /**
     * word
运行程序对象.
     */
    private ActiveXComponent wordApp = null;
    /**
     *
选定的范围或插入点.
     */
    private Dispatch selection;
    /**
     *
退出时是否保存文档.
     */
    private boolean saveOnExit = true;
 
    /**
     *
构造函数.
     * @param show
是否可见.
     */
    public WordBean(final boolean show) {
        if (wordApp == null) {
            wordApp =new ActiveXComponent("Word.Application");
           wordApp.setProperty("Visible", new Variant(show));
        }
    }
 
    /**
     *
设置退出时参数.
     * @param b boolean true-
退出时保存文件,false-退出时不保存文件
     */
    public void setSaveOnExit(
            finalboolean b) {
        this.saveOnExit = b;
    }
 
    /**
     *
把选定的内容或插入点向上移动.
     * @param pos
移动的距离
     */
    public void moveUp(
            final intpos) {
 
        if (selection == null) {
            selection =Dispatch.get(wordApp, "Selection").toDispatch();
        }
 
        for (int i = 0; i < pos; i++) {
           Dispatch.call(selection, "MoveUp");
        }
    }
 
    /**
     *
把选定的内容或者插入点向下移动.
     * @param pos
移动的距离
     */
    public void moveDown(
            final intpos) {
 
        if (selection == null) {
            selection =Dispatch.get(wordApp, "Selection").toDispatch();
        }
 
        for (int i = 0; i < pos; i++) {
           Dispatch.call(selection, "MoveDown");
        }
    }
 
    /**
     *
把选定的内容或者插入点向左移动.
     * @param pos
移动的距离
     */
    public void moveLeft(
            final intpos) {
 
        if (selection == null) {
            selection =Dispatch.get(wordApp, "Selection").toDispatch();
        }
 
        for (int i = 0; i < pos; i++) {
           Dispatch.call(selection, "MoveLeft");
        }
    }
 
    /**
     *
把选定的内容或者插入点向右移动.
     * @param pos
移动的距离
     */
    public void moveRight(
            final intpos) {
 
        if (selection == null) {
            selection =Dispatch.get(wordApp, "Selection").toDispatch();
        }
 
        for (int i = 0; i < pos; i++) {
           Dispatch.call(selection, "MoveRight");
        }
    }
 
    /**
     *
把插入点移动到文件首位置.
     */
    public void moveStart() {
        if (selection == null) {
            selection =Dispatch.get(wordApp, "Selection").toDispatch();
        }
 
        Dispatch.call(selection, "HomeKey",new Variant(6));
    }
 
    /**
     *
把插入点移动到文件尾位置.
     */
    public void moveEnd() {
        if (selection == null) {
            selection =Dispatch.get(wordApp, "Selection").toDispatch();
        }
 
        Dispatch.call(selection,"EndKey", new Variant(6));
    }
 
    /**
     *
增加缩进.
     * @param pos
缩进量
     */
    public void listIndent(
            final intpos) {
 
        Dispatch range =Dispatch.get(this.selection, "Range").toDispatch();
        Dispatch listFormat = Dispatch.get(range,"ListFormat").toDispatch();
        for (int i = 0; i < pos; i++) {
           Dispatch.call(listFormat, "ListIndent");
        }
    }
 
    /**
     *
减少缩进.
     * @param pos
缩进量
     */
    public void listOutdent(
            final intpos) {
 
        Dispatch range =Dispatch.get(this.selection, "Range").toDispatch();
        Dispatch listFormat =Dispatch.get(range, "ListFormat").toDispatch();
        for (int i = 0; i < pos; i++) {
           Dispatch.call(listFormat, "ListOutdent");
        }
    }
 
    /**
     *
回车换行.
     */
    public void enter() {
        int index = 1;
        while (true) {
            try {
               Dispatch.call(this.selection, "TypeParagraph");
               break;
            } catch(ComFailException e) {
               if (index++ >= MAX_RETRY) {
                   throw e;
               } else {
                   continue;
               }
            }
        }
    }
 
    /**
     *
插入一个换页符.
     */
    public void insertPageBreak() {
        Dispatch.call(this.selection,"InsertBreak", new Variant(2));
    }
 
    /**
     *
设置word文档是否可见.
     * @param isVisible
是否可见
     */
    public void setIsVisible(
            finalboolean isVisible) {
 
       wordApp.setProperty("Visible", new Variant(isVisible));
    }
 
    /**
     *
判断文档是否存在.
     * @param docName
文档名称.
     * @return boolean
是否存在.
     */
    private boolean isExist(
            final StringdocName) {
 
        boolean result = false;
        File file = new File(docName);
        result = file.exists();
        file = null;
        return result;
    }
 
    /**
     *
获取文件名称.
     * @param docName
文档路径.
     * @return
文件名称
     */
    public String getFileName(
            final StringdocName) {
 
        int pos = docName.lastIndexOf("//");
        return docName.substring(pos + 1);
    }
 
    /**
     *
打开文档.
     * @param docName
文档路径.
     * @throws WordException
异常
     */
    public void openDocument(
            final StringdocName)
    throws WordException {
 
        Dispatch docs =wordApp.getProperty("Documents").toDispatch();
 
        if (isExist(docName)) {
           this.closeDocument();
            doc =Dispatch.call(docs, "Open", docName).toDispatch();
        } else {
           wordApp.invoke("Quit", new Variant[] {});
            newWordException("[Open doc failed]: file["
                   + docName + "] isn't existed!");
        }
 
        selection = Dispatch.get(wordApp,"Selection").toDispatch();
    }
 
    /**
     *
添加一个新文档.
     * @param docName
文档路径.
     * @throws WordException
异常
     */
    public void newDocument(
            final StringdocName)
    throws WordException {
 
        try {
            Dispatchdocs = wordApp.getProperty("Documents").toDispatch();
            doc = Dispatch.call(docs,"Add").toDispatch();
            selection =Dispatch.get(wordApp, "Selection").toDispatch();
        } catch(com.jacob.com.ComFailException cfe) {
            throw newWordException(cfe.getMessage());
        } catch (com.jacob.com.ComExceptionce) {
            throw newWordException(ce.getMessage());
        }
    }
 
    /**
     *
插入一段文字.
     * @param textToInsert
文字
     * @param style
样式
     */
    public void insertText(
            final StringtextToInsert,
            final Stringstyle) {
 
        Dispatch.put(selection,"Text", textToInsert);
        Dispatch.put(selection,"Style", getOutlineStyle(style));
        Dispatch.call(selection,"MoveRight");
    }
 
    /**
     *
插入一个图片.
     * @param imagePath
图片路径.
     * @param style
图片样式
     */
    public void insertImage(
            final StringimagePath,
            final Stringstyle) {
 
       Dispatch.call(Dispatch.get(selection, "InLineShapes")
               .toDispatch(), "AddPicture", imagePath);
 
        Dispatch.call(selection,"MoveRight");
        Dispatch.put(selection,"Style", getOutlineStyle(style));
        this.enter();
    }
 
    /**
     *
获取对应名称的Style对象.
     * @param style Style
名称.
     * @return Style
对象
     */
    public Variant getOutlineStyle(
            final Stringstyle) {
 
        int index = 1;
        while (true) {
            try {
               return Dispatch.call(
                       Dispatch.get(this.doc, "Styles").toDispatch(),
                       "Item", new Variant(style));
            } catch(ComFailException e) {
               if (index++ >= MAX_RETRY) {
                   throw e;
               } else {
                   continue;
               }
            }
        }
    }
 
    /**
     *
插入标题.
     * @param text
标题文字.
     * @param style
设置标题的类型
     */
    public void insertOutline(
            final Stringtext,
            final Stringstyle) {
 
        this.insertText(text, style);
        this.enter();
    }
 
    /**
     *
插入目录.
     * tablesOfContents
的参数的含义 Add(Range As Range,[UseHeadingStyles],
     * [UpperHeadingLevel], [LowerHeadingLevel],[UseFields], [TableID],
     * --
这两个要不要都可以[RightAlignPageNumbers],[IncludePageNumbers], [AddedStyles],
     * --
这个参数必须有值,必须是数字,如果是其它,则报com.jacob.com.ComFailException
     * [UseHyperlinks],[HidePageNumbersInWeb],[UseOutlineLevels])
     */
    public void insertTablesOfContents() {
        Dispatch tablesOfContents =Dispatch.get(this.doc, "TablesOfContents")
               .toDispatch();
 
        Dispatch range =Dispatch.get(this.selection, "Range").toDispatch();
        // Dispatch.call
中的参数最多是9,如果超过9,请用Dispatch.callN或者Dispathc.invoke
        /*
         *Dispatch.invoke(tablesOfContents, "Add", Dispatch.Method,new
         * Object[]{range,newVariant(true),new Variant(1), new Variant(3),new
         * Variant(true), newVariant(true),new Variant(true) ,new
         * Variant("1"),newVariant(true),new Variant(true)},new int[10]);
         */
        Dispatch.callN(tablesOfContents,"Add", new Object[] {
               range,
               new Variant(true),
               new Variant(1),
               new Variant(3),
               new Variant(false),
               new Variant(true),
               new Variant(true),
               new Variant("1"),
               new Variant(true),
               new Variant(true)});
    }
 
    /**
     *
从选定内容或插入点开始查找文本.
     * @param toFindText
要查找的文本
     * @return boolean true-
查找到并选中该文本,false-未查找到文本
     */
    public boolean find(
            final StringtoFindText) {
 
        if (toFindText == null
               || toFindText.equals("")) {
            returnfalse;
        }
 
        //
selection所在位置开始查询
        Dispatch find =Dispatch.call(selection, "Find").toDispatch();
        //
设置要查找的内容
        Dispatch.put(find, "Text",toFindText);
        //
向前查找
        Dispatch.put(find,"Forward", "True");
        //
设置格式
        Dispatch.put(find,"Format", "True");
        //
大小写匹配
        Dispatch.put(find,"MatchCase", "True");
        //
全字匹配
        Dispatch.put(find,"MatchWholeWord", "True");
        //
查找并选中
        return Dispatch.call(find,"Execute").getBoolean();
    }
 
    /**
    *
把选定选定内容设定为替换文本.
    * @param toFindText
查找字符串
    * @param newText
要替换的内容
    * @return boolean true-
查找到并选中该文本,false-未查找到文本
    */
    public boolean replaceText(
            final StringtoFindText,
            final StringnewText) {
 
        if (!find(toFindText)) {
            returnfalse;
        }
 
        Dispatch.put(selection,"Text", newText);
        return true;
    }
 
    /**
     *
创建表格.
     * @param numCols
列数
     * @param numRows
行数
     * @param autoFormat
默认格式
     * @return
表格对象
     */
    public Dispatch createTable(
            final intnumRows,
            final intnumCols,
            final intautoFormat) {
 
        int index = 1;
        while (true) {
            try {
               Dispatch tables = Dispatch.get(doc, "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");
               Dispatch.call(newTable, "AutoFormat", new Variant(autoFormat));
               return newTable;
            } catch(ComFailException e) {
               if (index++ >= MAX_RETRY) {
                   throw e;
               } else {
                   continue;
               }
            }
        }
    }
 
    /**
     *
在指定的表头里填写数据.
     * @param table
表格
     * @param cellColIdx
列号
     * @param txt
文字
     * @param style
样式
     */
    public void putTableHeader(
            finalDispatch table,
            final intcellColIdx,
            final Stringtxt,
            final Stringstyle) {
 
        Dispatch cell = Dispatch.call(table,"Cell", new Variant(1),
               new Variant(cellColIdx)).toDispatch();
 
        Dispatch.call(cell,"Select");
        Dispatch.put(selection,"Text", txt);
        Dispatch.put(this.selection,"Style", getOutlineStyle(style));
    }
 
    /**
     *
在指定的单元格里填写数据.
     * @param table
表格
     * @param cellRowIdx
行号
     * @param cellColIdx
列号
     * @param txt
文字
     * @param style
样式
     */
    public void putTableCell(
            finalDispatch table,
            final intcellRowIdx,
            final intcellColIdx,
            final Stringtxt,
            final Stringstyle) {
 
        Dispatch cell = Dispatch.call(table,"Cell", new Variant(cellRowIdx),
               new Variant(cellColIdx)).toDispatch();
 
        Dispatch.call(cell,"Select");
        Dispatch.put(selection,"Text", txt);
        Dispatch.put(this.selection,"Style", getOutlineStyle(style));
    }
 
    /**
     *
关闭当前word文档.
     */
    private void closeDocument() {
        if (doc != null) {
           Dispatch.call(doc, "Save");
           Dispatch.call(doc, "Close", new Variant(saveOnExit));
            doc = null;
        }
    }
 
    /**
     *
文件保存或另存为.
     * @param savePath
保存或另存为路径
     */
    public void saveFileAs(
            final StringsavePath) {
 
        Dispatch.call(doc,"SaveAs", savePath);
    }
 
    /**
     *
关闭文档.
     */
    public void close() {
        closeDocument();
        if (wordApp != null) {
           Dispatch.call(wordApp, "Quit");
            wordApp =null;
        }
        selection = null;
    }
}