Java 实现 Excel 转 PDF,轻松搞定文档转换

该文章已生成可运行项目,

嘿,朋友!在实际的开发过程中,我们常常会遇到需要将 Excel 文件转换为 PDF 文件的需求。Java 提供了多种库和工具来实现这个功能,下面我将为你介绍一种常见的实现方式,使用 Apache POI 读取 Excel 文件,再使用 iText 生成 PDF 文件。

1. 引入所需的库

首先,我们需要在项目中引入 Apache POI 和 iText 相关的库。如果你使用的是 Maven 项目,就在 pom.xml 文件里添加以下依赖:



<!-- Apache POI 用于读取 Excel 文件 -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>5.2.3</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>5.2.3</version>
</dependency>

<!-- iText 用于生成 PDF 文件 -->
<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.5.13.3</version>
</dependency>

2. 实现 Excel 转 PDF 的代码

下面是具体的 Java 代码示例:



import com.itextpdf.text.*;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.*;

public class ExcelToPdfConverter {
    public static void main(String[] args) {
        try {
            // 读取 Excel 文件
            FileInputStream excelFile = new FileInputStream("input.xlsx");
            Workbook workbook = new XSSFWorkbook(excelFile);
            Sheet sheet = workbook.getSheetAt(0);

            // 创建 PDF 文档
            Document document = new Document();
            PdfWriter.getInstance(document, new FileOutputStream("output.pdf"));
            document.open();

            // 创建 PDF 表格,列数与 Excel 表格的列数相同
            int columnCount = sheet.getRow(0).getLastCellNum();
            PdfPTable pdfTable = new PdfPTable(columnCount);

            // 遍历 Excel 表格的每一行
            for (Row row : sheet) {
                // 遍历当前行的每一个单元格
                for (Cell cell : row) {
                    // 获取单元格的值
                    String cellValue = getCellValueAsString(cell);
                    // 创建 PDF 表格的单元格
                    PdfPCell pdfCell = new PdfPCell(new Phrase(cellValue));
                    // 将单元格添加到 PDF 表格中
                    pdfTable.addCell(pdfCell);
                }
            }

            // 将 PDF 表格添加到 PDF 文档中
            document.add(pdfTable);

            // 关闭文档和 Excel 文件
            document.close();
            workbook.close();
            excelFile.close();

            System.out.println("Excel 转 PDF 成功!");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("Excel 转 PDF 失败:" + e.getMessage());
        }
    }

    // 将单元格的值转换为字符串
    private static String getCellValueAsString(Cell cell) {
        if (cell == null) {
            return "";
        }
        switch (cell.getCellType()) {
            case STRING:
                return cell.getStringCellValue();
            case NUMERIC:
                if (DateUtil.isCellDateFormatted(cell)) {
                    return cell.getDateCellValue().toString();
                } else {
                    return String.valueOf(cell.getNumericCellValue());
                }
            case BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            case FORMULA:
                return cell.getCellFormula();
            default:
                return "";
        }
    }
}

3. 代码详细解释

  • 读取 Excel 文件

    • FileInputStream excelFile = new FileInputStream("input.xlsx");:创建一个 FileInputStream 对象,用于读取 input.xlsx 文件。

    • Workbook workbook = new XSSFWorkbook(excelFile);:使用 XSSFWorkbook 类创建一个 Workbook 对象,用于表示 Excel 文件。

    • Sheet sheet = workbook.getSheetAt(0);:获取 Excel 文件的第一个工作表。

  • 创建 PDF 文档

    • Document document = new Document();:创建一个 Document 对象,用于表示 PDF 文档。

    • PdfWriter.getInstance(document, new FileOutputStream("output.pdf"));:使用 PdfWriterDocument 对象与 FileOutputStream 关联起来,指定生成的 PDF 文件名为 output.pdf

    • document.open();:打开 PDF 文档,准备写入内容。

  • 创建 PDF 表格

    • int columnCount = sheet.getRow(0).getLastCellNum();:获取 Excel 表格第一行的列数。

    • PdfPTable pdfTable = new PdfPTable(columnCount);:创建一个 PdfPTable 对象,用于表示 PDF 表格,列数与 Excel 表格的列数相同。

  • 遍历 Excel 表格并填充 PDF 表格

    • for (Row row : sheet) {... }:遍历 Excel 表格的每一行。

    • for (Cell cell : row) {... }:遍历当前行的每一个单元格。

    • String cellValue = getCellValueAsString(cell);:调用 getCellValueAsString 方法将单元格的值转换为字符串。

    • PdfPCell pdfCell = new PdfPCell(new Phrase(cellValue));:创建一个 PdfPCell 对象,用于表示 PDF 表格的单元格。

    • pdfTable.addCell(pdfCell);:将 PdfPCell 对象添加到 PdfPTable 中。

  • 将 PDF 表格添加到 PDF 文档中

    • document.add(pdfTable);:将 PdfPTable 对象添加到 Document 中。

  • 关闭文档和 Excel 文件

    • document.close(); workbook.close(); excelFile.close();:关闭 PDF 文档、Excel 文件和输入流,释放资源。

4. 注意事项

  • 上述代码仅处理了 Excel 文件的第一个工作表,如果需要处理多个工作表,可以使用 workbook.getNumberOfSheets() 方法获取工作表的数量,然后遍历每个工作表进行处理。

  • 代码中的 getCellValueAsString 方法用于将不同类型的单元格值转换为字符串,确保在处理不同类型的单元格时不会出现异常。

嘿,朋友,通过以上的代码和解释,你应该已经掌握了如何使用 Java 将 Excel 文件转换为 PDF 文件。赶紧动手试试吧,让你的 Java 程序在文档转换方面更加得心应手!

本文章已经生成可运行项目
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

五行星辰

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值