java 將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目錄即可。運行結果就不截圖了。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章