
Java
Javaimport org.apache.poi.ss.usermodel.*;import org.apache.poi.xssf.usermodel.XSSFWorkbook;import com.itextpdf.text.Document;import com.itextpdf.text.pdf.PdfWriter;import Java.io.*;public class excelToPdfConverter { public static void mAIn(String[] args) { try { // 读取 excel 文件 FileInputStream fileInputStream = new FileInputStream("input.xlsx"); Workbook workbook = new XSSFWorkbook(fileInputStream); Sheet sheet = workbook.getSheetAt(0); // 创建 PDF 文档 Document document = new Document(); PdfWriter.getInstance(document, new FileOutputStream("output.pdf")); document.open(); // 遍历 excel 表格的每一行,并将数据写入 PDF 文档 for (Row row : sheet) { for (Cell cell : row) { String value = cell.getStringCellValue(); document.add(new com.itextpdf.text.Paragraph(value)); } } // 关闭文档和文件流 document.close(); fileInputStream.close(); System.out.println("excel 文件已成功转换为 PDF 文件!"); } catch (Exception e) { System.out.println("转换失败:" + e.getMessage()); e.printStackTrace(); } }}代码解析以上代码首先通过 FileInputStream 读取 excel 文件,然后创建 XSSFWorkbook 对象来表示整个 excel 文档。通过调用 getSheetAt(0) 方法获取第一个工作表对象。然后,我们创建一个 Document 对象来表示 PDF 文档,并使用 PdfWriter 将其与输出文件关联。调用 document.open() 方法打开文档。接下来,我们使用嵌套的 for 循环遍历 excel 表格的每一行和每一个单元格,将单元格的值写入 PDF 文档中。最后,我们调用 document.close() 方法关闭文档,并关闭文件流。本文介绍了如何使用 Java Apache POI 和 iText 将 excel 文件另存为 PDF 文件。通过使用这两个库的强大功能,我们可以轻松地实现 excel 文件到 PDF 文件的转换。希望本文能对你有所帮助!Copyright © 2025 IZhiDa.com All Rights Reserved.
知答 版权所有 粤ICP备2023042255号