Jacob工具类使用文件互转服务 word转html html转excel word转pdf excel转pdf ppt转pdf

前提条件 必须安装MSoffice

1.jdk使用jdk1.8

2.jacob.dll放在..\jdk1.8\jre\bin目录下

3.eclipse的jre版本要和jdk一致,window->preferences->java->compiler勾选jdk 1.8

4.window->preferences->java->InstalledJREs->Add 配置成jdk1.8.0_22版本 然后勾选上 点击ok、

5.在项目目录下新建lib目录,将jacob.jar文件拷贝到该目录下,点build path->configbuild path ->libraries

1)Add JARs->选择lib目录下的jacob.jar点击Ok

2)移除项目原来的JRE System Library ,AddLibrary->JRE System Library 选择之前添加的jdk1.6.0_22 ,点击finish

点击ok,libraries配置完毕

备注:3.出现Can'tco-create object问题,可能是之前调用dll后,没有释放资源,需要加入如下代码

先导入importcom.jacob.com.ComThread;//在jacob1.9版本里有这个类,1.6和1.7版本经测试无法导入此类

ComThread.InitSTA();// 初始化COM线程

// 以下操作word代码

MSWordManager ms=new MSWordManager(false);

//生成一个MSwordManager对象,并且设置显示Word程序

ms.openDocument("D:\\12.doc");

//创建一个新的.doc文件

ms.putTxtToCell(1, 1, 2, "!!!!");

//插入文本

ms.save("D:\\12.doc");

//保存.doc文件

ms.close();

ms.closeDocument();

// 以上操作word代码

ComThread.Release();// 操作完成后,释放COM线程

4.以下代码可以避免上述Can't co-create object问题

,在finally中释放资源

ActiveXComponentapp = new ActiveXComponent("Word.Application"); // 启动word

StringinFile = "D:\\123.doc"; // 要替换的word文件

try{

app.setProperty("Visible",new Variant(false)); // 设置word不可见

Dispatchdocs = app.getProperty("Documents").toDispatch();

Dispatchdoc = Dispatch.invoke(

docs,

"Open",

Dispatch.Method,

newObject[] { inFile, new Variant(false),

newVariant(false) }, new int[1]).toDispatch();

//打开word文件,注意这里第三个参数要设为false,这个参数表示是否以只读方式打开,

//因为我们要保存原文件,所以以可写方式打开。

Dispatchselection = app.getProperty("Selection").toDispatch();// 获得对Selection组件

Dispatch.call(selection,"HomeKey", new Variant(6));// 移到开头

Dispatchfind = Dispatch.call(selection, "Find").toDispatch();// 获得Find组件

Dispatch.put(find,"Text", "name"); // 查找字符串"name"

Dispatch.call(find,"Execute"); // 执行查询

Dispatch.put(selection,"Text", "111"); // 替换为"111"

Dispatchfind1 = Dispatch.call(selection, "Find").toDispatch();// 获得Find组件

Dispatch.call(selection,"HomeKey", new Variant(6));// 移到开头

Dispatch.put(find1,"Text", "8位随机生成密码"); // 查找字符串

Dispatch.call(find1,"Execute"); // 执行查询

Dispatch.put(selection,"Text", "222");

StringnewFileName = "D:\\temp.doc";

Dispatch.call(doc,"SaveAs", newFileName); // 另存文件

Dispatch.call(doc,"Close", new Variant(false));

System.out.println("isover");

}catch (Exception e) {

e.printStackTrace();

}finally {

app.invoke("Quit",new Variant[] {});

app.safeRelease();

}

5.workspace中的代码要求D盘根目录下有123.doc文件才能运行,否则会一致搜索不到相关词汇

工具类:

package com.guige.base.util;

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

import java.util.Date;

/**
 * TODO
 *
 * @author songaw
 * @date 2018/5/17 9:54
 */
public class JacobUtil {
    //word转PDF
    private static final String wdFormatPDF="17";
    //html转xls
    private static final String htmlFormatExcel="51";
    //PPT 转pdf
    private static final String pptFormatPDF="32";
    //excel转PDF
    private static final String xlTypePDF="0";

    /**
     * html转excel
     * @param srcFilePath
     * @param targetFilePath
     * @return
     */
    public static boolean htmlToExcel(String srcFilePath, String targetFilePath) {
        ActiveXComponent app = null;
        Dispatch excel = null;
        try {
             app = new ActiveXComponent("Excel.Application");
            System.out.println("*****正在转换...*****");
            // 设置Excel应用程序不可见
            app.setProperty("Visible", false);
            // Workbooks表示Excel程序的所有文档窗口,(
            app.setProperty("AutomationSecurity", new Variant(3)); // 禁用宏
            Dispatch excels = app.getProperty("Workbooks").toDispatch();
            //打开要转换的Excel文件
            excel = Dispatch.call(excels, "Open", srcFilePath, false,
                    true).toDispatch();
            //设置兼容性检查为false
            Dispatch.put(excel, "CheckCompatibility", false);
            app.setProperty("DisplayAlerts",false);
            Dispatch.invoke(excel, "SaveAs", Dispatch.Method, new Object[]{targetFilePath, new Variant(htmlFormatExcel)}, new int[1]);
            app.setProperty("DisplayAlerts",true);
            System.out.println("*****转换成功...*****");
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            if (excel != null) {
                Dispatch.call(excel, "Close", false);
            }
            if (app != null) {
                app.invoke("Quit", new Variant[] {});
                //app.invoke("Quit", 0);
            }
            ComThread.Release();
        }
    }

    /**
     * word转pdf
     * @param srcFilePath
     * @param targetFilePath
     * @return
     */
    public static boolean docToPdf(String srcFilePath, String targetFilePath) {
        ActiveXComponent app = null;
        Dispatch doc = null;
        try {
            ComThread.InitSTA();
            app = new ActiveXComponent("Word.Application");
            System.out.println("*****正在转换...*****");
            app.setProperty("Visible", false);
            Dispatch docs = app.getProperty("Documents").toDispatch();
            doc = Dispatch.invoke(docs, "Open", Dispatch.Method,
                    new Object[] { srcFilePath,
                            new Variant(false),
                            new Variant(true),//是否只读
                            new Variant(false),
                            new Variant("pwd") },
                    new int[1]).toDispatch();
             //Dispatch.put(doc, "CheckCompatibility", false);  //兼容性检查,为特定值false不正确
            Dispatch.put(doc, "RemovePersonalInformation", false);
            app.setProperty("DisplayAlerts",false);
            Dispatch.call(doc, "ExportAsFixedFormat", targetFilePath, wdFormatPDF); // word保存为pdf格式宏,值为17
            app.setProperty("DisplayAlerts",true);
            System.out.println("*****转换成功...*****");
            return true; // set flag true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            if (doc != null) {
                Dispatch.call(doc, "Close", false);
            }
            if (app != null) {
                app.invoke("Quit", 0);
            }

            ComThread.Release();
        }
    }
    public static boolean pptToPdf(String srcFilePath, String pdfFilePath) {
        ActiveXComponent app = null;
        Dispatch ppt = null;
        try {
            ComThread.InitSTA();
            app = new ActiveXComponent("PowerPoint.Application");
            System.out.println("*****正在转换...*****");
            Dispatch ppts = app.getProperty("Presentations").toDispatch();

            // 因POWER.EXE的发布规则为同步,所以设置为同步发布
            ppt = Dispatch.call(ppts, "Open", srcFilePath, true,// ReadOnly
                    true,// Untitled指定文件是否有标题
                    false// WithWindow指定文件是否可见
            ).toDispatch();
            //Dispatch.put(ppt, "CheckCompatibility", false);  //兼容性检查,为特定值false不正确
            app.setProperty("DisplayAlerts",false);
            Dispatch.call(ppt, "SaveAs", pdfFilePath, pptFormatPDF); //ppSaveAsPDF为特定值32
            app.setProperty("DisplayAlerts",true);
            System.out.println("*****转换成功...*****");
            return true; // set flag true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            if (ppt != null) {
                Dispatch.call(ppt, "Close");
            }
            if (app != null) {
                app.invoke("Quit");
            }
            ComThread.Release();
        }
    }
    public static boolean excelToPDF(String srcFilePath, String pdfFilePath) {
        ActiveXComponent app = null;
        Dispatch excel = null;
        try {

            ComThread.InitSTA(true);
             app = new ActiveXComponent("Excel.Application");
            System.out.println("*****正在转换...*****");
            long date = new Date().getTime();
            app.setProperty("Visible", false);
            app.setProperty("AutomationSecurity", new Variant(3)); // 禁用宏
            Dispatch excels = app.getProperty("Workbooks").toDispatch();

             excel = Dispatch
                    .invoke(excels, "Open", Dispatch.Method,
                            new Object[] { srcFilePath, new Variant(false), new Variant(false) }, new int[9])
                    .toDispatch();
            // 转换格式
            Dispatch.put(excel, "CheckCompatibility", false);
            app.setProperty("DisplayAlerts",false);
            Dispatch.invoke(excel, "ExportAsFixedFormat", Dispatch.Method, new Object[] { new Variant(0), // PDF格式=0
                    pdfFilePath, new Variant(xlTypePDF) // 0=标准 (生成的PDF图片不会变模糊) 1=最小文件
                    // (生成的PDF图片糊的一塌糊涂)
            }, new int[1]);
            app.setProperty("DisplayAlerts",true);
            System.out.println("*****转换成功...*****");
            // 这里放弃使用SaveAs
            /*
             * Dispatch.invoke(excel,"SaveAs",Dispatch.Method,new Object[]{
             * outFile, new Variant(57), new Variant(false), new Variant(57),
             * new Variant(57), new Variant(false), new Variant(true), new
             * Variant(57), new Variant(true), new Variant(true), new
             * Variant(true) },new int[1]);
             */

            return true;
        } catch (Exception e) {
            e.printStackTrace();
            // TODO: handle exception
            return false;
        }finally {
            if (excel != null) {
                Dispatch.call(excel, "Close", false);
            }
            if (app != null) {
                app.invoke("Quit", new Variant[] {});
                //app.invoke("Quit", 0);
            }
            ComThread.Release();
        }
    }
}

相关推荐