您的位置:首页 > 其它

Excel转PDF的相关问题处理

2016-04-21 23:52 267 查看
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. 好了,走起,成功。

洗洗睡了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: