Java操作word文档使用JACOB和POI操作word,Excel,PPT需要的jar包

简介:

使用方式:

复制代码
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Arrays;
import com.jacob.activeX.ActiveXComponent;

public class WriteDoc2 {
    public static void main(String[] args) {
        //在正式批量跑之前,做单个word文档的测试.
        WordUtils util = new WordUtils(true);
        util.openDocument("C:\\Users\\ABC\\Desktop\\test.docx");
        util.setSaveOnExit(true);
        util.insertText("xxx444dddd4x");
        util.saveAs("C:\\Users\\ABC\\Desktop\\test.docx");
        util.closeDocument();
    }
}
复制代码

对应WordUtils.java工具类,我是使用的如下: 

复制代码
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;

public class WordUtils {

    // word运行程序对象
    private ActiveXComponent word;
    // 所有word文档集合
    private Dispatch documents;
    // word文档
    private Dispatch doc;
    // 选定的范围或插入点
    private Dispatch selection;
    // 保存退出
    private boolean saveOnExit;

    public WordUtils(boolean visible) {
        word = new ActiveXComponent("Word.Application");
        word.setProperty("Visible", new Variant(visible));
        documents = word.getProperty("Documents").toDispatch();
    }

    /**
     * 设置退出时参数
     * 
     * @param saveOnExit
     *            boolean true-退出时保存文件,false-退出时不保存文件     
     */
    public void setSaveOnExit(boolean saveOnExit) {
        this.saveOnExit = saveOnExit;
    }

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

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

    /**
     * 打开一个有密码保护的word文档
     * @param docPath
     * @param password
     */
    public void openDocument(String docPath, String password) {
        doc = Dispatch.call(documents, "Open", docPath).toDispatch();
        unProtect(password);
        selection = Dispatch.get(word, "Selection").toDispatch();
    }
    
    /**
     * 去掉密码保护
     * @param password
     */
    public void unProtect(String password){
        try{
            String protectionType = Dispatch.get(doc, "ProtectionType").toString();
            if(!"-1".equals(protectionType)){
                Dispatch.call(doc, "Unprotect", password);
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }
    
    /**
     * 添加密码保护
     * @param password
     */
    public void protect(String password){
        String protectionType = Dispatch.get(doc, "ProtectionType").toString();
        if("-1".equals(protectionType)){
            Dispatch.call(doc, "Protect",new Object[]{new Variant(3), new Variant(true), password});
        }
    }
    
    /**
     * 显示审阅的最终状态
     */
    public void showFinalState(){
        Dispatch.call(doc, "AcceptAllRevisionsShown");
    }
    
    /**
      * 打印预览:
      */
     public void printpreview() {
        Dispatch.call(doc, "PrintPreView");
     }
    
    /**
     * 打印
     */
    public void print(){
        Dispatch.call(doc, "PrintOut");
    }
    
    public void print(String printerName) {
        word.setProperty("ActivePrinter", new Variant(printerName));
        print();
    }
    
    /**
     * 指定打印机名称和打印输出工作名称
     * @param printerName
     * @param outputName
     */
    public void print(String printerName, String outputName){
        word.setProperty("ActivePrinter", new Variant(printerName));
        Dispatch.call(doc, "PrintOut", new Variant[]{new Variant(false), new Variant(false), new Variant(0), new Variant(outputName)});
    }

    /**
     * 把选定的内容或插入点向上移动
     * 
     * @param pos
     */
    public void moveUp(int pos) {
        move("MoveUp", pos);
    }

    /**
     * 把选定的内容或者插入点向下移动
     * 
     * @param pos
     */
    public void moveDown(int pos) {
        move("MoveDown", pos);
    }

    /**
     * 把选定的内容或者插入点向左移动
     * 
     * @param pos
     */
    public void moveLeft(int pos) {
        move("MoveLeft", pos);
    }

    /**
     * 把选定的内容或者插入点向右移动
     * 
     * @param pos
     */
    public void moveRight(int pos) {
        move("MoveRight", pos);
    }
    
    /**
     * 把选定的内容或者插入点向右移动
     */
    public void moveRight() {
        Dispatch.call(getSelection(), "MoveRight");
    }

    /**
     * 把选定的内容或者插入点向指定的方向移动
     * @param actionName
     * @param pos
     */
    private void move(String actionName, int pos) {
        for (int i = 0; i < pos; i++)
            Dispatch.call(getSelection(), actionName);
    }
    
    /**
     * 把插入点移动到文件首位置
     */
    public void moveStart(){
        Dispatch.call(getSelection(), "HomeKey", new Variant(6));
    }
    
    /**
     * 把插入点移动到文件末尾位置
     */
    public void moveEnd(){
        Dispatch.call(getSelection(), "EndKey", new Variant(6));
    }

    /**
     * 插入换页符
     */
    public void newPage(){
        Dispatch.call(getSelection(), "InsertBreak");
    }
    
    public void nextPage(){
        moveEnd();
        moveDown(1);
    }
    
    public int getPageCount(){
        Dispatch selection = Dispatch.get(word, "Selection").toDispatch();
        return Dispatch.call(selection,"information", new Variant(4)).getInt();
    }
    
    /**
     * 获取当前的选定的内容或者插入点
     * @return 当前的选定的内容或者插入点
     */
    public Dispatch getSelection(){
        if (selection == null)
            selection = Dispatch.get(word, "Selection").toDispatch();
        return selection;
    }
    
    /**
     * 从选定内容或插入点开始查找文本
     * @param findText 要查找的文本
     * @return boolean true-查找到并选中该文本,false-未查找到文本
     */
    public boolean find(String findText){
        if(findText == null || findText.equals("")){
            return false;
        }
        // 从selection所在位置开始查询
        Dispatch find = Dispatch.call(getSelection(), "Find").toDispatch();
        // 设置要查找的内容
        Dispatch.put(find, "Text", findText);
        // 向前查找
        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 findText
     * @param newText
     * @return boolean true-查找到并替换该文本,false-未查找到文本
     */
    public boolean replaceText(String findText, String newText){
        moveStart();
        if (!find(findText))
            return false;
        Dispatch.put(getSelection(), "Text", newText);
        return true;
    }
    
    /**
     * 进入页眉视图
     */
    public void headerView(){
        //取得活动窗体对象   
        Dispatch ActiveWindow = word.getProperty( "ActiveWindow").toDispatch();   
        //取得活动窗格对象   
        Dispatch ActivePane = Dispatch.get(ActiveWindow, "ActivePane").toDispatch();   
        //取得视窗对象   
        Dispatch view = Dispatch.get(ActivePane, "View").toDispatch();
        Dispatch.put(view, "SeekView", "9");
    }
    
    /**
     * 进入页脚视图
     */
    public void footerView(){
        //取得活动窗体对象   
        Dispatch ActiveWindow = word.getProperty( "ActiveWindow").toDispatch();   
        //取得活动窗格对象   
        Dispatch ActivePane = Dispatch.get(ActiveWindow, "ActivePane").toDispatch();   
        //取得视窗对象   
        Dispatch view = Dispatch.get(ActivePane, "View").toDispatch();
        Dispatch.put(view, "SeekView", "10");
    }
    
    /**
     * 进入普通视图
     */
    public void pageView(){
        //取得活动窗体对象   
        Dispatch ActiveWindow = word.getProperty( "ActiveWindow").toDispatch();   
        //取得活动窗格对象   
        Dispatch ActivePane = Dispatch.get(ActiveWindow, "ActivePane").toDispatch();   
        //取得视窗对象   
        Dispatch view = Dispatch.get(ActivePane, "View").toDispatch();
        Dispatch.put(view, "SeekView", new Variant(0));//普通视图
    }
    
    /**
     * 全局替换文本
     * @param findText
     * @param newText
     */
    public void replaceAllText(String findText, String newText){
        int count = getPageCount();
        for(int i = 0; i < count; i++){
            headerView();
            while (find(findText)){
                Dispatch.put(getSelection(), "Text", newText);
                moveEnd();
            }
               footerView();
            while (find(findText)){
                Dispatch.put(getSelection(), "Text", newText);
                moveStart();
            }
            pageView();
            moveStart();
            while (find(findText)){
                Dispatch.put(getSelection(), "Text", newText);
                moveStart();
            }
            nextPage();
        }
    }
    
    /**
     * 全局替换文本
     * @param findText
     * @param newText
     */
    public void replaceAllText(String findText, String newText, String fontName, int size){
        /****插入页眉页脚*****/  
        //取得活动窗体对象   
        Dispatch ActiveWindow = word.getProperty( "ActiveWindow").toDispatch();   
        //取得活动窗格对象   
        Dispatch ActivePane = Dispatch.get(ActiveWindow, "ActivePane").toDispatch();   
        //取得视窗对象   
        Dispatch view = Dispatch.get(ActivePane, "View").toDispatch();   
        /****设置页眉*****/  
        Dispatch.put(view, "SeekView", "9");  
        while (find(findText)){
            Dispatch.put(getSelection(), "Text", newText);
            moveStart();
        }
        /****设置页脚*****/  
        Dispatch.put(view, "SeekView", "10");
        while (find(findText)){
            Dispatch.put(getSelection(), "Text", newText);
            moveStart();
        }
        Dispatch.put(view, "SeekView", new Variant(0));//恢复视图
        moveStart();
        while (find(findText)){
            Dispatch.put(getSelection(), "Text", newText);
            putFontSize(getSelection(), fontName, size);
            moveStart();
        }
    }
    
    /**
     * 设置选中或当前插入点的字体
     * @param selection
     * @param fontName
     * @param size
     */
    public void putFontSize(Dispatch selection, String fontName, int size){
        Dispatch font = Dispatch.get(selection, "Font").toDispatch();
        Dispatch.put(font, "Name", new Variant(fontName));
        Dispatch.put(font, "Size", new Variant(size));
    }
    
    /**
     * 在当前插入点插入字符串
     */
    public void insertText(String text){
        Dispatch.put(getSelection(), "Text", text);
    }
    
    /**
     * 将指定的文本替换成图片
     * @param findText
     * @param imagePath
     * @return boolean true-查找到并替换该文本,false-未查找到文本
     */
    public boolean replaceImage(String findText, String imagePath, int width, int height){
        moveStart();
        if (!find(findText))
            return false;
        Dispatch picture = Dispatch.call(Dispatch.get(getSelection(), "InLineShapes").toDispatch(), "AddPicture", imagePath).toDispatch();
        Dispatch.call(picture, "Select");
        Dispatch.put(picture, "Width", new Variant(width));
        Dispatch.put(picture, "Height", new Variant(height));
        moveRight();
        return true;
    }
    
    /**
     * 全局将指定的文本替换成图片
     * @param findText
     * @param imagePath
     */
    public void replaceAllImage(String findText, String imagePath, int width, int height){
        moveStart();
        while (find(findText)){
            Dispatch picture = Dispatch.call(Dispatch.get(getSelection(), "InLineShapes").toDispatch(), "AddPicture", imagePath).toDispatch();
            Dispatch.call(picture, "Select");
            Dispatch.put(picture, "Width", new Variant(width));
            Dispatch.put(picture, "Height", new Variant(height));
            moveStart();
        }
    }
    
    /**
     * 在当前插入点中插入图片
     * @param imagePath
     */
    public void insertImage(String imagePath, int width, int height){
        Dispatch picture = Dispatch.call(Dispatch.get(getSelection(), "InLineShapes").toDispatch(), "AddPicture", imagePath).toDispatch();
        Dispatch.call(picture, "Select");
        Dispatch.put(picture, "Width", new Variant(width));
        Dispatch.put(picture, "Height", new Variant(height));
        moveRight();
    }
    
    /**
     * 在当前插入点中插入图片
     * @param imagePath
     */
    public void insertImage(String imagePath){
        Dispatch.call(Dispatch.get(getSelection(), "InLineShapes").toDispatch(), "AddPicture", imagePath);
    }
    
    /**
     * 获取书签的位置
     * @param bookmarkName
     * @return 书签的位置
     */
    public Dispatch getBookmark(String bookmarkName){
        try{
            Dispatch bookmark = Dispatch.call(this.doc, "Bookmarks", bookmarkName).toDispatch();
            return Dispatch.get(bookmark, "Range").toDispatch();
        }catch(Exception e){
            e.printStackTrace();
        }
        return null;
    }
    
    /**
     * 在指定的书签位置插入图片
     * @param bookmarkName
     * @param imagePath
     */
    public void insertImageAtBookmark(String bookmarkName, String imagePath){
        Dispatch dispatch = getBookmark(bookmarkName);
        if(dispatch != null)
        Dispatch.call(Dispatch.get(dispatch, "InLineShapes").toDispatch(), "AddPicture", imagePath);
    }
    
    /**
     * 在指定的书签位置插入图片
     * @param bookmarkName
     * @param imagePath
     * @param width
     * @param height
     */
    public void insertImageAtBookmark(String bookmarkName, String imagePath, int width, int height){
        Dispatch dispatch = getBookmark(bookmarkName);
        if(dispatch != null){
        Dispatch picture = Dispatch.call(Dispatch.get(dispatch, "InLineShapes").toDispatch(), "AddPicture", imagePath).toDispatch();
        Dispatch.call(picture, "Select");
        Dispatch.put(picture, "Width", new Variant(width));
        Dispatch.put(picture, "Height", new Variant(height));
        }
    }
    
    /**
     * 在指定的书签位置插入文本
     * @param bookmarkName
     * @param text
     */
    public void insertAtBookmark(String bookmarkName, String text){
        Dispatch dispatch = getBookmark(bookmarkName);
        if(dispatch != null)
            Dispatch.put(dispatch, "Text", text);
    }
    
    /**
     * 文档另存为
     * @param savePath
     */
    public void saveAs(String savePath){
        Dispatch.call(doc, "SaveAs", savePath);
    }
    
    /**
     * 文档另存为PDF
     * <b><p>注意:此操作要求word是2007版本或以上版本且装有加载项:Microsoft Save as PDF 或 XPS</p></b>
     * @param savePath
     */
    public void saveAsPdf(String savePath){
        Dispatch.call(doc, "SaveAs", new Variant(17));
    }
    
    /**
     * 保存文档
     * @param savePath
     */
    public void save(String savePath){
        Dispatch.call(Dispatch.call(word, "WordBasic").getDispatch(),"FileSaveAs", savePath);
    }
    
    /**
     * 关闭word文档
     */
    public void closeDocument(){
        if (doc != null) {
            Dispatch.call(doc, "Close", new Variant(saveOnExit));
            doc = null;
        }
    }
    
    public void exit(){
        word.invoke("Quit", new Variant[0]);  
    }
}
复制代码

具体WordUtils类的使用暂时没有看到更多的例子,上面的util的使用是自己摸索出来的,可能不是最优,最恰当的.

//==================================================================================================

使用Java工具POI操作MicroSoft Office套件Word,Excle和PPT使用Maven工程的话需要在Pom.xml文件中引入的jar包.

一开始是想使用POI工具操作,但是从网上找来的代码始终报编译错误,代码中的一些类找不到,但是也明明已经引入了poi-3.x.jar包文件,更换了好几个poi版本的jar包仍是一样的效果.

随后调查,到底需要哪些jar包.....结果如下:

复制代码
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi</artifactId>
        <version>3.8</version>
    </dependency>
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml</artifactId>
        <version>3.8</version>
    </dependency>
    <dependency>
        <groupId>org.apache.xmlbeans</groupId>
        <artifactId>xmlbeans</artifactId>
        <version>2.3.0</version>
    </dependency>
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-scratchpad</artifactId>
        <version>3.8</version>
    </dependency> 
复制代码

所依赖的全部jar包的截图

如果只引入一个poi-3.x.jar包是会报错的.  POI具体操作Word,Excel,和PPT的代码,自行百度.只要jar包引入的正确,运行编译代码就没有问题.

 



本文转自SummerChill博客园博客,原文链接:http://www.cnblogs.com/DreamDrive/p/7090284.html,如需转载请自行联系原作者

相关文章
|
8月前
|
小程序
公众号如何添加附传Word、Excel、Pdf、PPT文档
公众号里添加一些文档给公众号粉丝下载,比如课件PPT、申请表Word文档、岗位需求Excel表、大赛入围/获奖名单等。公众号本身是不支持直接上传文件的,但我们可以通过附件小程序“间接”上传文件。
1328 0
|
Java API Apache
Java编程如何读取Word文档里的Excel表格,并在保存文本内容时保留表格的样式?
【10月更文挑战第29天】Java编程如何读取Word文档里的Excel表格,并在保存文本内容时保留表格的样式?
1192 5
|
12月前
|
人工智能 算法 安全
使用CodeBuddy实现批量转换PPT、Excel、Word为PDF文件工具
通过 CodeBuddy 实现本地批量转换工具,让复杂的文档处理需求转化为 “需求描述→代码生成→一键运行” 的极简流程,真正实现 “技术为效率服务” 的目标。感兴趣的快来体验下把
820 10
|
Java 中间件 测试技术
java依赖冲突解决问题之jar包版本冲突无法通过升降级解决时如何解决
java依赖冲突解决问题之jar包版本冲突无法通过升降级解决时如何解决
|
人工智能 自然语言处理 JavaScript
Univer:开源全栈 AI 办公工具,支持 Word、Excel、PPT 等文档处理和多人实时协作
Univer 是一款开源的 AI 办公工具,支持 Word、Excel 等文档处理的全栈解决方案。它具有强大的功能、高度的可扩展性和跨平台兼容性,适用于个人和企业用户,能够显著提高工作效率。
3198 9
Univer:开源全栈 AI 办公工具,支持 Word、Excel、PPT 等文档处理和多人实时协作
|
数据处理 Python
Python实用记录(十):获取excel数据并通过列表的形式保存为txt文档、xlsx文档、csv文档
这篇文章介绍了如何使用Python读取Excel文件中的数据,处理后将其保存为txt、xlsx和csv格式的文件。
825 3
Python实用记录(十):获取excel数据并通过列表的形式保存为txt文档、xlsx文档、csv文档
|
数据采集 分布式计算 Java
Kettle的Java开发环境需要什么jar包?
【10月更文挑战第24天】Kettle的Java开发环境需要什么jar包?
555 2
|
Java Apache Maven
Java将word文档转换成pdf文件的方法?
【10月更文挑战第13天】Java将word文档转换成pdf文件的方法?
5533 1
|
JSON 数据格式
LangChain-20 Document Loader 文件加载 加载MD DOCX EXCEL PPT PDF HTML JSON 等多种文件格式 后续可通过FAISS向量化 增强检索
LangChain-20 Document Loader 文件加载 加载MD DOCX EXCEL PPT PDF HTML JSON 等多种文件格式 后续可通过FAISS向量化 增强检索
1713 2
内存或磁盘不足,excel无法再次打开或保存任何文档
内存或磁盘不足,excel无法再次打开或保存任何文档
527 2

热门文章

最新文章