Java可以使用Apache POI和iText两个库来实现Excel转PDF的功能。
这里是使用iText的方式
添加依赖
XML
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.2.3</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext7-core</artifactId>
<version>7.1.16</version>
</dependency>
下面是一个使用Apache POI将Excel转换为PDF的示例代码:
java
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Paragraph;
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.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class Test {
public static void main(String[] args) {
String excelFilePath = "F:\\tmp\\input.xlsx"; // 输入的Excel文件路径
String pdfFilePath = "F:\\tmp\\output.pdf"; // 输出的PDF文件路径
try {
convertExcelToPdf(excelFilePath, pdfFilePath);
System.out.println("转换成功!");
} catch (IOException e) {
e.printStackTrace();
}
}
private static void convertExcelToPdf(String excelFilePath, String pdfFilePath) throws IOException {
Workbook workbook = new XSSFWorkbook(new FileInputStream(excelFilePath));
PdfWriter writer = new PdfWriter(new FileOutputStream(pdfFilePath));
PdfDocument pdfDoc = new PdfDocument(writer);
Document document = new Document(pdfDoc);
// 设置中文字体
PdfFont font = PdfFontFactory.createFont("STSongStd-Light", "UniGB-UCS2-H", true);
for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
Sheet sheet = workbook.getSheetAt(i);
document.add(new Paragraph("Sheet: " + sheet.getSheetName()).setFont(font));
for (Row row : sheet) {
StringBuilder rowData = new StringBuilder();
for (Cell cell : row) {
switch (cell.getCellType()) {
case STRING:
rowData.append(cell.getStringCellValue()).append(" ");
break;
case NUMERIC:
rowData.append(cell.getNumericCellValue()).append(" ");
break;
case BOOLEAN:
rowData.append(cell.getBooleanCellValue()).append(" ");
break;
default:
rowData.append(" ");
}
}
document.add(new Paragraph(rowData.toString().trim()).setFont(font));
}
document.add(new Paragraph("\n")); // 分隔不同的工作表
}
document.close();
workbook.close();
}
}
注意,以上示例代码中的input.xlsx是输入的Excel文件名,output.pdf是输出的PDF文件名。
pdf生成时需要设置字体,否则生成的pdf中,中文将无法显示。