save excel as pdf

2804 단어 Excel
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();
		}
	}

}

좋은 웹페이지 즐겨찾기