Excel转PDF的相关问题处理

本文介绍如何使用Jacob库将Excel文件转换为PDF格式,并分享了解决过程中遇到的问题及解决方案。

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

1. 用的是jacob-1.18.jar, 

2. 选择相应的 jacob-1.18-x64.dll 或jacob-1.18-x86.dll 放到3个地方,第一个是jdk/bin,第二个是jdk/jre/bin,第三个是C:\Windows\System32

3. 直接代码了:

public static void excelToPdf(String excelFileName, String pdfFileName, int Orientation) {
		ComThread.InitSTA();
		ActiveXComponent app = new ActiveXComponent("Excel.Application");
		try {
			app.setProperty("Visible", new Variant(false));
			Dispatch workbooks = app.getProperty("Workbooks").toDispatch();
			Dispatch workbook = Dispatch.invoke(workbooks, "Open", 1, 
					new Object[] { excelFileName, new Variant(false),new Variant(false) }, 
					new int[3]).toDispatch();

			Dispatch currentSheet = Dispatch.get(workbook, "ActiveSheet").toDispatch();
			Dispatch page = Dispatch.get(currentSheet, "PageSetup").toDispatch();
			Dispatch.put(page, "PrintArea", false);
			Dispatch.put(page, "Orientation", Orientation);
			Dispatch.put(page, "PaperSize", Integer.valueOf(9));

			Dispatch.put(page, "Zoom", false);

			Dispatch.put(page, "FitToPagesTall", false);
			Dispatch.put(page, "FitToPagesWide", 1);
			Variant f = new Variant(false);
			String tempFile = "E:\\ZJN\\ZJN_FILES\\";
			File tempDir = new File(tempFile);
			if (!tempDir.exists()) {
				tempDir.mkdirs();
			}
			tempFile = tempFile + "temp.pdf";
			Dispatch.invoke(workbook, "SaveAs", Dispatch.Method, new Object[] { tempFile,
					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]);
			
			File file = new File(tempFile);
			file.renameTo(new File(pdfFileName));
			file.delete();
			Dispatch.call(workbook, "Close", f);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (app != null) {
				app.invoke("Quit", new Variant[0]);
			}

			ComThread.Release();
			System.gc();
			System.runFinalization();
		}
	}

我当时做到这里,程序起来后总是报异常:

Source: Microsoft Office Excel  

Description: 类 Workbook 的 SaveAs 方法无效

网上查了很多,最后在高人的指点下,解决了问题


4. 重点来了,问题是这么解决的:

下载office2007 能另存为pdf的插件 SaveAsPDFandXPS.exe 安装,也就是说要安装SaveAsPDFandXPS.exe,就这个货,坑死我了。

5. 好了,走起,成功。


洗洗睡了。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值