首页 > 编程语言 >java excel转pdf

java excel转pdf

时间:2024-10-28 14:41:54浏览次数:4  
标签:java String excel Variant Dispatch pdf jacob new com

使用jacob实现Excel转PDF

在使用jacob之前需要做一些准备,首先需要去下载jacob的压缩包jacob.zip ,下载地址:https://github.com/freemansoft/jacob-project/releases/download/Root_B-1_21/jacob-1.21.zip

解压之后,得到如下内容:

 

1、如果你是64位系统就用 x64的dll,32位系统就用x86的dll。之后我们需要将dll文件放入放入你的jdk的bin目录下。

2、将jacob.jar导入项目中。

 

 

 

package pdf;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;

import java.io.File;

public class JacobExcelToPDF {

/**
* 使用jacob实现excel转PDF
*
* @param inputFilePath 导入Excel文件路径
* @param outputFilePath 导出PDF文件路径
*/
public static void jacobExcelToPDF(String inputFilePath, String outputFilePath) {
ActiveXComponent ax = null;
Dispatch excel = null;

try {
ComThread.InitSTA();
ax = new ActiveXComponent("Excel.Application");
ax.setProperty("Visible", new Variant(false));
//禁用宏
ax.setProperty("AutomationSecurity", new Variant(3));

Dispatch excels = ax.getProperty("Workbooks").toDispatch();

Object[] obj = {
inputFilePath,
new Variant(false),
new Variant(false)
};

excel = Dispatch.invoke(excels, "Open", Dispatch.Method, obj, new int[9]).toDispatch();

//转换格式
Object[] obj2 = {
//PDF格式等于0
new Variant(0),
outputFilePath,
//0=标准(生成的PDF图片不会模糊),1=最小的文件
new Variant(0)
};

Dispatch.invoke(excel, "ExportAsFixedFormat", Dispatch.Method, obj2, new int[1]);
System.out.println("转换成功\t"+ outputFilePath.split("\\\\")[3]);

} catch (Exception e) {
e.printStackTrace();
throw e;
} finally {
if (excel != null) {
Dispatch.call(excel, "Close", new Variant(false));
}
if (ax != null) {
ax.invoke("Quit", new Variant[]{});
ax = null;
}
ComThread.Release();
}
}


public static void main(String[] args) {
String filePath = "F:\\111\\CS1";
File file = new File(filePath);
File[] files = file.listFiles((dir, name) -> name.toLowerCase().endsWith(".xlsx"));
if (files != null){
for (File f : files){
String fileName = f.getName();
String fileName2 = fileName.substring(0, fileName.lastIndexOf("."));
String inputFilePath2 = filePath + "\\" + fileName;
String outputFilePath2 = filePath + "\\" + fileName2 + ".pdf";
jacobExcelToPDF(inputFilePath2, outputFilePath2);
}
}
}
}

 

标签:java,String,excel,Variant,Dispatch,pdf,jacob,new,com
From: https://www.cnblogs.com/lt3232696/p/18510598

相关文章