java 將excel檔案轉換成pdf檔案

來源:互聯網
上載者:User

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目錄即可

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.