java excel转pdf

一、使用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);
}
}
}
}

二、使用ITextPDF实现excel转pdf(推荐)
package pdf;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfWriter;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
* Excel转换为PDF
*/
public class ExcelToPdfConverter {
public static void convertExcelToPdf(String excelFilePath, String pdfOutputPath) throws IOException, DocumentException {
// 创建PDF文档对象
Document document = new Document();
// 创建PdfWriter对象,并附加到PDF文档对象
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(pdfOutputPath));
document.open();

// 创建支持中文的字体实例
BaseFont baseFont = null;
try {
baseFont = BaseFont.createFont("C:\\Windows\\Fonts\\simsun.ttc,1", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
} catch (DocumentException e) {
e.printStackTrace();
}
Font font = new Font(baseFont, 12, Font.NORMAL); // 使用支持中文的字体

// 使用Apache POI读取Excel文件
try (FileInputStream inputStream = new FileInputStream(new File(excelFilePath))) {
Workbook workbook = new XSSFWorkbook(inputStream);
// 读取Excel数据
Sheet sheet = workbook.getSheetAt(0);

int numColumns = sheet.getRow(0).getLastCellNum();
int numRows = sheet.getLastRowNum() + 1;

for (int rowIndex = 0; rowIndex < numRows; rowIndex++) {
StringBuilder line = new StringBuilder();
Row row = sheet.getRow(rowIndex);
for (int colIndex = 0; colIndex < numColumns; colIndex += 4) {
if (colIndex + 3 < numColumns) {
line.append(getCellValue(row, colIndex)).append(" ")
.append(getCellValue(row, colIndex + 1)).append(" ")
.append(getCellValue(row, colIndex + 2)).append(" ")
.append(getCellValue(row, colIndex + 3)).append("\n");
} else {
// 如果剩余列数不足4列
for (int i = colIndex; i < numColumns; i++) {
line.append(getCellValue(row, i)).append(" ");
}
line.append("\n");
}
}
document.add(new Paragraph(line.toString(), font));
}
}

// 关闭PDF文档对象和输出流
document.close();
writer.close();
}

private static String getCellValue(Row row, int colIndex) {
if (row == null) {
return "";
}
Cell cell = row.getCell(colIndex);
if (cell == null) {
return "";
}
switch (cell.getCellType()) {
case STRING:
return cell.getStringCellValue();
case NUMERIC:
return String.valueOf(cell.getNumericCellValue());
case BOOLEAN:
return String.valueOf(cell.getBooleanCellValue());
default:
return "";
}
}
public static void main(String[] args) {
int count = 0;
try {

List<String> excelFilePaths = new ArrayList<>();

String filePath = "F:\\111\\CS1\\CS3";
File file = new File(filePath);
File[] files = file.listFiles(((dir, name) -> name.toLowerCase().endsWith(".xlsx")));
if (files != null){
for (File f : files){
String excelFilePath = f.getAbsolutePath();
//excelFilePaths.add(excelFilePath);
String[] paths = excelFilePath.split("\\\\");
String pdfOutputPath = paths[0] + "\\" + paths[1] + "\\" + paths[2] + "\\CS3\\" + paths[4].replace(".xlsx", ".pdf");
convertExcelToPdf(excelFilePath, pdfOutputPath);
System.out.println("Excel to PDF conversion completed"+paths[4].replace(".xlsx", ".pdf")+" successfully."+(++count));
}
}
} catch (IOException | DocumentException e) {
e.printStackTrace();
}
}
}
三、使用aspose.cells实现excel转pdf。(不推荐
  
好用,但免费版每次只能转100个,且转换后pdf有aspose.cells水印。

 

posted on 2024-10-28 14:51  0o好好先生o0  阅读(3)  评论(0编辑  收藏  举报

导航