1. 用的是jacob-1.18.jar,
2. 選擇相應的 jacob-1.18-x64.dll 或jacob-1.18-x86.dll 放到3個地方,第一個是jdk/bin,第二個是jdk/jre/bin,第三個是C:\Windows\System32
3. 直接代碼了:
public static void excelToPdf(String excelFileName, String pdfFileName, int Orientation) {
ComThread.InitSTA();
ActiveXComponent app = new ActiveXComponent("Excel.Application");
try {
app.setProperty("Visible", new Variant(false));
Dispatch workbooks = app.getProperty("Workbooks").toDispatch();
Dispatch workbook = Dispatch.invoke(workbooks, "Open", 1,
new Object[] { excelFileName, new Variant(false),new Variant(false) },
new int[3]).toDispatch();
Dispatch currentSheet = Dispatch.get(workbook, "ActiveSheet").toDispatch();
Dispatch page = Dispatch.get(currentSheet, "PageSetup").toDispatch();
Dispatch.put(page, "PrintArea", false);
Dispatch.put(page, "Orientation", Orientation);
Dispatch.put(page, "PaperSize", Integer.valueOf(9));
Dispatch.put(page, "Zoom", false);
Dispatch.put(page, "FitToPagesTall", false);
Dispatch.put(page, "FitToPagesWide", 1);
Variant f = new Variant(false);
String tempFile = "E:\\ZJN\\ZJN_FILES\\";
File tempDir = new File(tempFile);
if (!tempDir.exists()) {
tempDir.mkdirs();
}
tempFile = tempFile + "temp.pdf";
Dispatch.invoke(workbook, "SaveAs", Dispatch.Method, new Object[] { tempFile,
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]);
File file = new File(tempFile);
file.renameTo(new File(pdfFileName));
file.delete();
Dispatch.call(workbook, "Close", f);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (app != null) {
app.invoke("Quit", new Variant[0]);
}
ComThread.Release();
System.gc();
System.runFinalization();
}
}
我當時做到這裏,程序起來後總是報異常:
Source: Microsoft Office Excel
Description: 類 Workbook 的 SaveAs 方法無效
網上查了很多,最後在高人的指點下,解決了問題
4. 重點來了,問題是這麼解決的:
下載office2007 能另存爲pdf的插件 SaveAsPDFandXPS.exe 安裝,也就是說要安裝SaveAsPDFandXPS.exe,就這個貨,坑死我了。
5. 好了,走起,成功。
洗洗睡了。