Java使用Jacob操作word

近期项目需要根据word模板动态生成word文档,在网上看了些资料,在介绍的几种方法中选择了jacob方式,根据网上的资料,能解决大部分的问题,比如,生成表格,设置字体、段落格式,插入图片、设置图片格式。

可是项目中生成的word 文档还需要生成目录页,分割章节,网上找了很多资料,都没找到相关的方法,最后看到一篇博客,提供了一个思路,Java通过jacob操作office的宏,加上之前有过写宏的经验,一步步的实验终于搞定了。

博客地址:http://men4661273.iteye.com/blog/2097871

package com.jacob.newdemo;

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

public class WordBean {
    // word文档
    private Dispatch doc;
    // word运行程序对象
    private ActiveXComponent word;
    // 所有word文档集合
    private Dispatch documents;
    // 选定的范围或插入点
    private Dispatch selection;
    private boolean saveOnExit = true;

    /**
     * @param visible
     *            true表示word应用程序可见
     */
    public WordBean(boolean visible) {
        // TODO Auto-generated constructor stub
        if (word == null) {
            word = new ActiveXComponent("Word.Application");
            word.setProperty("Visible", new Variant(visible));
        }
        if (documents == null)
            documents = word.getProperty("Documents").toDispatch();
    }

    /**
     * 创建一个新的word文档
     */
    public void createNewDocument() {
        doc = Dispatch.call(documents, "Add").toDispatch();
        selection = Dispatch.get(word, "Selection").toDispatch();
    }

    /**
     * 打开一个已存在的文档
     *
     * @param docPath
     */
    public void openDocument(String docPath) {
        closeDocument();
        doc = Dispatch.call(documents, "Open", docPath).toDispatch();
        selection = Dispatch.get(word, "Selection").toDispatch();
    }

    /**
     * 把选定的内容或插入点向上移动
     *
     * @param pos
     *            移动的距离
     */
    public void moveUp(int pos) {
        if (selection == null)
            selection = Dispatch.get(word, "Selection").toDispatch();
        for (int i = 0; i < pos; i++)
            Dispatch.call(selection, "MoveUp");
    }

    /**
     * 把选定的内容或者插入点向下移动
     *
     * @param pos
     *            移动的距离
     */
    public void moveDown(int pos) {
        if (selection == null)
            selection = Dispatch.get(word, "Selection").toDispatch();
        for (int i = 0; i < pos; i++)
            Dispatch.call(selection, "MoveDown");
    }

    /**
     * 把选定的内容或者插入点向左移动
     *
     * @param pos
     *            移动的距离
     */
    public void moveLeft(int pos) {
        if (selection == null)
            selection = Dispatch.get(word, "Selection").toDispatch();
        for (int i = 0; i < pos; i++) {
            Dispatch.call(selection, "MoveLeft");
        }
    }

    /**
     * 把选定的内容或者插入点向右移动
     *
     * @param pos
     *            移动的距离
     */
    public void moveRight(int pos) {
        if (selection == null)
            selection = Dispatch.get(word, "Selection").toDispatch();
        for (int i = 0; i < pos; i++)
            Dispatch.call(selection, "MoveRight");
    }

    /**
     * 把插入点移动到文件首位置
     */
    public void moveStart() {
        if (selection == null)
            selection = Dispatch.get(word, "Selection").toDispatch();
        Dispatch.call(selection, "HomeKey", new Variant(6));
    }

    public void moveEnd() {
        if (selection == null)
            selection = Dispatch.get(word, "Selection").toDispatch();
        Dispatch.call(selection, "EndKey", new Variant(6));
    }

    /**
     * 向 document 中插入文本内容
     *
     * @param textToInsert
     *            插入的文本内容
     */
    public void insertText(String textToInsert) {
        // 在指定的位置插入文本内容
        Dispatch.put(selection, "Text", textToInsert);
        // 取消选中,应该就是移动光标
        Dispatch format = Dispatch.get(selection, "ParagraphFormat").toDispatch();
        // 设置段落格式为首行缩进2个字符
        Dispatch.put(format, "CharacterUnitFirstLineIndent", new Variant(2));
        Dispatch.call(selection, "MoveRight", new Variant(1), new Variant(1));
        //moveRight(1);
        Dispatch.call(selection, "TypeParagraph");// 插入一个空行
        //Dispatch.call(selection, "MoveUp");
        //moveDown(1);
    }

    /**
     * 插入标题
     * @param num  标题编号
     * @param level 标题级别:-2:一级标题;-3:二级标题;-4:三级标题;-5:四级标题
     * @param text 标题题目
     */
    public void insertTitle(String num, int level, String text) {
        Dispatch activeDocument = Dispatch.get(word, "ActiveDocument").toDispatch();

        //Dispatch.call(selection, "TypeParagraph");// 插入一个空行
        //moveDown(1);
        Dispatch.put(selection, "Text", num + " " + text);
        Dispatch style = Dispatch.call(activeDocument, "Styles", new Variant(level)).toDispatch();;
        Dispatch.put(selection, "Style", style);
        moveRight(1);
        Dispatch.call(selection, "TypeParagraph");// 插入一个空行
        //moveDown(1);
    }

    /**
     * 创建目录
     */
    public void createCatalog() {
        Dispatch activeDocument = Dispatch.get(word, "ActiveDocument").toDispatch();

        Dispatch.call(selection, "HomeKey", new Variant(6)); // 将光标移到文件首的位置
        Dispatch.call(selection, "TypeParagraph");// 插入一个空行
        moveUp(1);

        Dispatch.put(selection, "Text", "目录");
        Dispatch style = Dispatch.call(activeDocument, "Styles", new Variant(-2)).toDispatch();;
        Dispatch.put(selection, "Style", style);
        Dispatch alignment = Dispatch.get(selection, "ParagraphFormat").toDispatch();// 段落格式
        Dispatch.put(alignment, "Alignment", "1"); // (1:置中 2:靠右 3:靠左)
        moveRight(1);
        Dispatch.call(selection, "TypeParagraph");// 插入一个空行

        Dispatch myRange = Dispatch.call(selection, "Range").toDispatch();

        /** 获取目录 */
        Dispatch tablesOfContents = Dispatch.get(activeDocument, "TablesOfContents").toDispatch();

        Dispatch add = Dispatch.call(tablesOfContents, "Add", myRange, new Variant(true),
                new Variant(1), new Variant(3), new Variant(true), new Variant(true), new Variant('T'),
                new Variant(true), new Variant(true), new Variant(1), new Variant(true)).toDispatch();

//        Dispatch.put(add, "RightAlignPageNumbers", new Variant(true));
//        Dispatch.put(add, "UseHeadingStyles", new Variant(true));
//        Dispatch.put(add, "UpperHeadingLevel", new Variant(1));
//        Dispatch.put(add, "LowerHeadingLevel", new Variant(3));
//        Dispatch.put(add, "IncludePageNumbers", new Variant(true));
//        Dispatch.put(add, "UseHyperlinks", new Variant(true));
//        Dispatch.put(add, "HidePageNumbersInWeb", new Variant(true));

//        Dispatch.call(add, "Add", myRange);

        //插入一个分页符
        Dispatch.call(selection, "InsertBreak", new Variant(7));
        Dispatch.call(selection, "TypeBackspace");
    }

    /**
     * 更新目录
     * @param outputPath
     * @param doc
     */
    public void updateCatalog(String outputPath, Dispatch doc) {
        /** 打开word文档 */
        //Dispatch doc = Dispatch.invoke(documents, "Open", Dispatch.Method,
        //        new Object[] { outputPath, new Variant(false), new Variant(true) }, new int[1]).toDispatch();
        //Dispatch doc = Dispatch.call(documents, "Open", outputPath).toDispatch();

        Dispatch activeDocument = word.getProperty("ActiveDocument").toDispatch();
        /** 获取目录 */
        Dispatch tablesOfContents = Dispatch.get(activeDocument, "TablesOfContents").toDispatch();
        /** 获取第一个目录。若有多个目录,则传递对应的参数  */
        Variant tablesOfContent = Dispatch.call(tablesOfContents, "Item", new Variant(1));
        /** 更新目录,有两个方法:Update 更新域,UpdatePageNumbers 只更新页码 */
        Dispatch toc = tablesOfContent.toDispatch();
        toc.call(toc, "Update");

        /** 另存为 */
        Dispatch.call(Dispatch.call(word, "WordBasic").getDispatch(), "FileSaveAs", outputPath);
        //System.out.println("更新目录");
        /** 关闭word文档 */
        Dispatch.call(doc, "Close", new Variant(false));

        /** 退出word进程 */
        close();
    }

    /**
     * 在当前插入点插入图片
     *
     * @param imagePath
     *            图片路径
     */
    public void insertImage(String imagePath, int c, int tc, String title) {
        Dispatch.call(Dispatch.get(selection, "InLineShapes").toDispatch(), "AddPicture", imagePath);

        Dispatch.call(selection, "TypeParagraph");// 插入一个空行
        Dispatch alignment = Dispatch.get(selection, "ParagraphFormat").toDispatch();// 段落格式
        Dispatch.put(alignment, "Alignment", "1"); // (1:置中 2:靠右 3:靠左)
        //moveRight(1);
        putText("图" + c + "-" + tc + " " + title);
        moveRight(1);
        Dispatch.call(selection, "TypeParagraph");// 插入一个空行
    }

    public void insertBlankRow() {
        Dispatch.call(selection, "TypeParagraph");// 插入一个空行
        Dispatch alignment = Dispatch.get(selection, "ParagraphFormat").toDispatch();// 段落格式
        Dispatch.put(alignment, "Alignment", "3"); // (1:置中 2:靠右 3:靠左)
    }

    /**
     * 创建表格
     *
     * @param cols
     *            列数
     * @param rows
     *            行数
     */
    public void createTable(int numCols, int numRows, int c, int tc, String title) {
//        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");
//        moveEnd();

        Dispatch.call(selection, "TypeParagraph");// 插入一个空行
        Dispatch alignment = Dispatch.get(selection, "ParagraphFormat").toDispatch();// 段落格式
        Dispatch.put(alignment, "Alignment", "1"); // (1:置中 2:靠右 3:靠左)
        putText("表" + c + "-" + tc + " " + title);
        moveRight(1);
        Dispatch.call(selection, "TypeParagraph");// 插入一个空行

        Dispatch activeDocument = Dispatch.get(word, "ActiveDocument").toDispatch();
        Dispatch tables1 = Dispatch.get(activeDocument, "Tables").toDispatch();

        Dispatch range = Dispatch.get(selection, "Range").toDispatch();
        Dispatch.call(tables1, "Add", range, new Variant(numRows), new Variant(numCols), new Variant(1), new Variant(0)).toDispatch();

        Dispatch.call(selection, "MoveDown", new Variant(5), new Variant(numRows), new Variant(1));
        Dispatch format = Dispatch.get(selection, "ParagraphFormat").toDispatch();
        Dispatch.put(format, "Alignment", new Variant(1));

        moveLeft(1);
    }

    /**
     * 向选中的单元格中写入数据
     * @param text
     */
    public void putText(String text) {
        Dispatch.put(selection, "Text", text);
    }

    /**
     * 增加一行
     *
     * @param tableIndex
     *            word文档中的第N张表(从1开始)
     */
    public void addRow(int tableIndex) {
        Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();
        // 要填充的表格
        Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex)).toDispatch();
        // 表格的所有行
        Dispatch rows = Dispatch.get(table, "Rows").toDispatch();
        Dispatch.call(rows, "Add");
    }

    /**
     * 合并单元格
     *
     * @param tableIndex
     * @param fstCellRowIdx
     * @param fstCellColIdx
     * @param secCellRowIdx
     * @param secCellColIdx
     */
    public void mergeCell(int tableIndex, int fstCellRowIdx, int fstCellColIdx, int secCellRowIdx, int secCellColIdx) {
        // 所有表格
        Dispatch tables = Dispatch.get(doc, "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 tableIndex
     * @param cellRowIdx
     * @param cellColIdx
     * @param txt
     */
    public void putTxtToCell(int tableIndex, int cellRowIdx, int cellColIdx, String txt) {
        // 所有表格
        Dispatch tables = Dispatch.get(doc, "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.put(selection, "Text", txt);
    }

    /**
     * 增加一列
     *
     * @param tableIndex
     *            word文档中的第N张表(从1开始)
     */
    public void addCol(int tableIndex) {
        // 所有表格
        Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();
        // 要填充的表格
        Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex)).toDispatch();
        // 表格的所有行
        Dispatch cols = Dispatch.get(table, "Columns").toDispatch();
        Dispatch.call(cols, "Add").toDispatch();
        Dispatch.call(cols, "AutoFit");
    }

    /**
     * 设置当前选定内容的字体
     *
     * @param boldSize
     * @param italicSize
     * @param underLineSize
     *            下划线
     * @param colorSize
     *            字体颜色
     * @param size
     *            字体大小
     * @param name
     *            字体名称
     */
    public void setFont(boolean bold, boolean italic, boolean underLine, String colorSize, String size, String name) {
        Dispatch font = Dispatch.get(selection, "Font").toDispatch();
        Dispatch.put(font, "Name", new Variant(name));
        Dispatch.put(font, "Bold", new Variant(bold));
        Dispatch.put(font, "Italic", new Variant(italic));
        Dispatch.put(font, "Underline", new Variant(underLine));
        Dispatch.put(font, "Color", colorSize);
        Dispatch.put(font, "Size", size);
    }

    /**
     * 文件保存或另存为
     *
     * @param savePath
     *            保存或另存为路径
     */
    public void save(String savePath) {
        Dispatch.call((Dispatch) Dispatch.call(word, "WordBasic").getDispatch(), "FileSaveAs", savePath);
    }

    /**
     * 关闭当前word文档
     */
    public void closeDocument() {
        if (doc != null) {
            Dispatch.call(doc, "Save");
            Dispatch.call(doc, "Close", new Variant(saveOnExit));
            doc = null;
        }
    }

    /**
     * 关闭全部应用
     */
    public void close() {
        closeDocument();
        if (word != null) {
            Dispatch.call(word, "Quit");
            word = null;
        }
        selection = null;
        documents = null;
    }
}
时间: 2024-10-24 05:48:15

Java使用Jacob操作word的相关文章

主题:jacob操作word excel

项目开发过程中,需求涉及到了各种文档转换为HTML或者网页易显示格式,现在将实现方式整理如下:  一.了解Jacob 先了解一下概念,JACOB 就是 JAVA-COM Bridge的缩写,提供自动化的访问com的功能,也是通过JNI功能访问windows平台下的com组件或者win32系统库的.这是一个开始于1999年的开源项目的成果,有很多使用者对该项目进行了修改,做出了自己的贡献. 下载地址:http://sourceforge.net/project/showfiles.php?grou

在Java中如何操作word, excel, pdf文件

java操作word,excel,pdf 在平常应用程序中,对office和pdf文档进行读取数据是比较常见的功能,尤其在很多web应用程序中.所以今天我们就简单来看一下java对word.excel.pdf文件的读取.本篇博客只是讲解简单应用.如果想深入了解原理.请读者自行研究一些相关源码. 首先我们来认识一下读取相关文档的jar包: 1. 引用POI包读取word文档内容 poi.jar 下载地址 http://apache.freelamp.com/poi/release/bin/poi-

jacob 操作word

1. 首先下载jacob-1.18.zip,解压后有两个文件jacob.jar 和 jacob.dll.需要把jacob.jar放到你工程的classpath中并且把jacob.dll放到jdk的bin目录下(D:\Program Files\Java\jdk1.8.0_101\bin)目录下或者系统的system32其他相应的目录下. 2.下面是提供的工具类 1 package com.erqiao.rc.util; 2 3 import com.jacob.activeX.ActiveXCo

Java 使用 jacob 将 word 文档转换为 pdf 文件

网上查询了许许多多的博客,说利用 poi.iText.Jsoup.jdoctopdf.使用 jodconverter 来调用 openOffice 的服务来转换等等,我尝试了很多种,但要么显示不完全,要么可是可能有问题,使用这个 jacob 的方法我最开始是最不想用的,因为它要导入 dll 文件,但最后我还是选择了使用该方法,原因是感觉转换后的 pdf 文件简直就是完美. jacob 缺点:需要 window 环境,而且速度是最慢的需要安装 msofficeWord 以及 SaveAsPDFan

Java使用Jacob将Word、Excel、PPT转化成PDF

使用Jacob将金山WPS转化成PDF,其中WPS文字使用KWPS.Aplication.Excel表格是KET.Application.演示文档是KWPP.Application,废话不多说,直接上代码: 1 import com.jacob.activeX.ActiveXComponent; 2 import com.jacob.com.ComThread; 3 import com.jacob.com.Dispatch; 4 import com.jacob.com.Variant; 5

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 Ad

Java 操作Word表格

本文将对如何在Java程序中操作Word表格作进一步介绍.操作要点包括 如何在Word中创建嵌套表格. 对已有表格添加行或者列 复制已有表格中的指定行或者列 对跨页的表格可设置是否禁止跨页断行 创建表格,包括添加数据.插入表格.合并单元格.设置表格样式.单元格居中.单元格背景色,单元格字体样式等设置,可参考这篇文章里的内容. 使用工具:Free Spire.Doc for Java (免费版) Jar文件可通过官网下载jar文件包,下载后,解压文件,将lib文件夹下的Spire.Doc.jar导

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

ava调用com组件操作word使用总结(jacob) 简单描述 在此处输入简单摘要 特别声明:使用java-com技术可以完成任何VBA可以完成的office文档操作; 一.准备工作 先了解一下概念,JACOB 就是 JAVA-COM Bridge的缩写,提供自动化的访问com的功能,也是通过JNI功能访问windows平台下的com组件或者win32系统库的.这是一个开始于 1999年的开源项目的成果,有很多使用者对该项目进行了修改,做出了自己的贡献. Jacob下载地址: http://s

Jacob操作office文档(Word,PPT,Excel)

public boolean doc2pdf(String srcFilePath, String pdfFilePath) { ActiveXComponent app = null; Dispatch doc = null; try { ComThread.InitSTA(); app = new ActiveXComponent("Word.Application"); app.setProperty("Visible", false); Dispatch d