注意事项:使用此方法需安装Office
import java.io.File;
import java.util.Date;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
public class Excel2PdfUtil {
public static void main(String[] args) {
int time = Ex2PDF("D:/report.xls", "D:/report2.pdf");
System.out.println(time);
}
public static int Ex2PDF(String inputFile, String pdfFile) {
// 0=标准 (生成的PDF图片不会变模糊) 1=最小文件(生成的PDF图片糊的一塌糊涂)
final int xlTypePDF = 0;
// try {
// User32.SetWinEventHook(new UINT(0x0003), new UINT(0x0003), 0, 0, new DWORD(0), new DWORD(0), new UINT(0));
// } catch (IllegalAccessException e1) {
// e1.printStackTrace();
// } catch (NativeException e1) {
// e1.printStackTrace();
// }
ComThread.InitSTA(true);
ActiveXComponent ax = new ActiveXComponent("Excel.Application");
long date = new Date().getTime();
ax.setProperty("Visible", new Variant(false));
ax.setProperty("AutomationSecurity", new Variant(3)); // 禁用宏
try {
Dispatch excels = ax.getProperty("Workbooks").toDispatch();
Dispatch excel = Dispatch.invoke(excels, "Open", Dispatch.Method, new Object[] { inputFile, new Variant(false), new Variant(false) },
new int[9]).toDispatch();
File tofile = new File(pdfFile);
if (tofile.exists()) {
tofile.delete();
}
// 转换格式
Dispatch.invoke(excel, "ExportAsFixedFormat", Dispatch.Method, new Object[] {
new Variant(0), // PDF格式=0
pdfFile, new Variant(xlTypePDF), Variant.VT_MISSING, Variant.VT_MISSING, Variant.VT_MISSING, Variant.VT_MISSING,
new Variant(false), Variant.VT_MISSING }, new int[1]);
// 这里放弃使用SaveAs
/*
* Dispatch.invoke(excel,"SaveAs",Dispatch.Method,new Object[]{
* outFile, 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]);
*/
long date2 = new Date().getTime();
int time = (int) ((date2 - date) / 1000);
Dispatch.call(excel, "Close", new Variant(false));
return time;
} catch (Exception e) {
e.printStackTrace();
return -1;
} finally {
if (ax != null) {
ax.invoke("Quit", new Variant[] {});
ax = null;
}
ComThread.Release();
}
}
}
工程下载地址:https://download.csdn.net/download/zheng_chang_wei/10883954
工程中包括Jacob jar包,jacob-1.18-x64.dll和jacob-1.18-x32.dll,修改main函数中excel和PDF地址后可直接运行。