用jacoba操作office后,发现代码中的 app.invoke("Quit", new Variant[] {}); 不能正确关闭进程,解决方法是:将方法放在ComThread中最后关闭ComThread
/**
* 将Excel转换成PDF
* @param excelPath
* @param pdfPath
*/
public static void Excel2PDF(String excelPath,String pdfPath)
{
ComThread.InitSTA();
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:" + excelPath);
Dispatch workbook = Dispatch.invoke(workbooks, "Open", Dispatch.Method, new Object[]{excelPath, new Variant(false),new Variant(false)}, new int[3]).toDispatch();
Dispatch.invoke(workbook, "SaveAs", Dispatch.Method, new Object[] {
pdfPath, 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 " + pdfPath);
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[] {});
}
}
ComThread.Release();
}