1.下载jar包:
jacob-1.7.jar,见附件
将.dll文件放到system32文件夹下
2.实现类
import java.io.*;
import java.util.Calendar;
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 ExcelToPdf {
private String path;
public ExcelToPdf(String path) {
this.path = path;
}
public void saveExcelAsPdf(String filePath, String outFile) {
ComThread.InitSTA();
ActiveXComponent actcom = new ActiveXComponent("Excel.Application");
try {
System.out.println((new Date()).toString()
+ " start convert from : " + filePath + " to " + outFile);
actcom.setProperty("Visible", new Variant(false));
Dispatch excels = actcom.getProperty("Workbooks").toDispatch();
Dispatch excel = Dispatch.invoke(
excels,
"Open",
Dispatch.Method,
new Object[] { filePath, new Variant(false),
new Variant(false) }, new int[9]).toDispatch();
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(false),
new Variant(true), new Variant(false) }, new int[1]);
Dispatch.call(excel, "Close", new Variant(false));
if (actcom != null) {
actcom.invoke("Quit", new Variant[] {});
actcom = null;
}
ComThread.Release();
System.out.println((new Date()).toString() + " convert ok : "
+ filePath + " to " + outFile);
} catch (Exception es) {
es.printStackTrace();
}
}
3.测试类
import java.io.File;
public class Test{
public static void main(String[] args) throws Exception {
String path = "C:/A.xls";
System.out.println("Convert Path : " + path);
try {
File file = new File(path);
if (file.exists()) {
ExcelToPdf et = new ExcelToPdf(path);
et.saveExcelAsPdf(path, "C:/S.pdf");
} else {
System.out.println("Path Not Exist,Pls Comfirm: " + path);
}
} catch (Exception ex) {
System.out
.println("Pls Check Your Format,Format Must Be: java com/olive/util/RunTask Path(Exist Path) Frequency(Run Frequency,int)");
ex.printStackTrace();
}
}
}