展会信息港展会大全

java 将excel文件转换成pdf文件
来源:互联网   发布日期:2016-01-19 13:00:23   浏览:1622次  

导读:最近做一个项目,需要把excel文件转换成pdf文件,经过我查资料,无非使用两种方式:1 POI+Itext 2 Jacob来调用excel另存功能。 第一种方式,原理是使用POI来读取excel的内容,将其写到pdf文件中。实现难度 ...

最近做一个项目,需要把excel文件转换成pdf文件,经过我查资料,无非使用两种方式:1 POI+Itext 2 Jacob来调用excel另存功能。

第一种方式,原理是使用POI来读取excel的内容,将其写到pdf文件中。实现难度有点大,主要是因为excel sheet结构不固定,内容也不固定,可能存在图片等,导致读excel比较复杂,真正实现还是比较复杂的。

第二种方式,原来是使用jacob来调用excel文件的另存为pdf的功能。主要是熟悉jacob的API即可。不需要精巧的编程技巧。

本文使用第二种方式,使用这种方式,需要在当前环境中安装office,pdf软件。建议安装office 2010版本。如果安装的07版本,还需要安装一个excel插件(SaveAsPDFandXPS.exe) 这个插件是微软官方的,链接如下:微软官方

package com.bplead.module.sign.util;

import com.jacob.activeX.ActiveXComponent;

import com.jacob.com.Dispatch;

import com.jacob.com.Variant;

public class TransferTool {

public static void els2pdf(String els,String pdf){

System.out.println("Starting excel...");

long start = System.currentTimeMillis();

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

try {

app.setProperty("Visible",false);

Dispatch workbooks = app.getProperty("Workbooks").toDispatch();

System.out.println("opening document:" + els);

Dispatch workbook = Dispatch.invoke(workbooks, "Open", Dispatch.Method, new Object[]{els, new Variant(false),new Variant(false)}, new int[3]).toDispatch();

Dispatch.invoke(workbook, "SaveAs", Dispatch.Method, new Object[] {

pdf, 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]);

Variant f = new Variant(false);

System.out.println("to pdf " + pdf);

Dispatch.call(workbook, "Close", f);

long end = System.currentTimeMillis();

System.out.println("completed..used:" + (end - start)/1000 + " s");

} catch (Exception e) {

System.out.println("========Error:Operation fail:" + e.getMessage());

}finally {

if (app != null){

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

}

}

}

public static void main(String[] args) {

els2pdf("f:ProjectTemplate.xlsx","f:pdf.pdf");

}

}

运行以上环境,需要下载jacob的包,该包还包含2个dll文件,一个是jacob-1.17-x64.dll,这个是64位的,还有一个是 jacob-1.17-x86.dll文件,这个是32位的。将jar包包含到classpath目录,dll文件包含到jre/bin目录即可

赞助本站

人工智能实验室

相关热词: excel文件 转换 pdf文件 java

AiLab云推荐
展开

热门栏目HotCates

Copyright © 2010-2024 AiLab Team. 人工智能实验室 版权所有    关于我们 | 联系我们 | 广告服务 | 公司动态 | 免责声明 | 隐私条款 | 工作机会 | 展会港