1、环境准备

在使用jacob之前需要做一些准备,首先需要去下载jacob的压缩包jacob.zip ,下载地址: https://sourceforge.net/projects/jacob-project/


解压之后,得到如下内容:




如果你是64位系统就用 x64的dll,32位系统就用x86的dll。之后我们需要将dll文件放入放入你的jdk的bin目录下,如下图所示:




这样前期准备工作就做好了,


接下来在在Maven中引入Jacob所需依赖:


<!--jacob依赖-->

        <dependency>

            <groupId>com.jacob</groupId>

            <artifactId>jacob</artifactId>

            <version>1.19</version>

            <scope>system</scope>

            <!--本地的jacob.jar的路径-->

            <systemPath>D:\DevInstall\jacob18,19\jacob-1.19\jacob.jar</systemPath>

        </dependency>

1.

2.

3.

4.

5.

6.

7.

8.

9.

注意:上面依赖中标签的值就是你的jacob.jar的具体路径,这个改成自己刚才下载的对应的路径就行了。


2、执行导出PDF

执行Excel导出PDF的方法如下:其中比较重要的地方进行了注释,方法可以直接拿来用即可!


/**

     * 使用jacob实现excel转PDF

     *

     * @param inputFilePath 导入Excel文件路径

     * @param outputFilePath 导出PDF文件路径

     */

    public static void jacobExcelToPDF(String inputFilePath, String outputFilePath) {

        ActiveXComponent ax = null;

        Dispatch excel = null;

 

        try {

            ComThread.InitSTA();

            ax = new ActiveXComponent("Excel.Application");

            ax.setProperty("Visible", new Variant(false));

   //禁用宏

            ax.setProperty("AutomationSecurity", new Variant(3));

 

            Dispatch excels = ax.getProperty("Workbooks").toDispatch();

 

            Object[] obj = {

                    inputFilePath,

                    new Variant(false),

                    new Variant(false)

            };

 

            excel = Dispatch.invoke(excels, "Open", Dispatch.Method, obj, new int[9]).toDispatch();

 

   //转换格式

            Object[] obj2 = {

                    //PDF格式等于0

                    new Variant(0),

                    outputFilePath,

                    //0=标准(生成的PDF图片不会模糊),1=最小的文件

                    new Variant(0)

            };

 

            Dispatch.invoke(excel, "ExportAsFixedFormat", Dispatch.Method, obj2, new int[1]);

 

        } catch (Exception e) {

            e.printStackTrace();

            throw e;

        } finally {

            if (excel != null) {

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

            }

            if (ax != null) {

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

                ax = null;

            }

            ComThread.Release();

        }

 

 

    }