save excel as pdf

本文介绍如何使用Jacob库将Excel文件转换为PDF格式。通过导入必要的库,实现了一个名为ExcelToPdf的类,该类包含一个方法用于打开Excel文件、将其保存为PDF并关闭Excel应用程序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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();
		}
	}

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值