【Excel & PDF 系列】POI + iText 库实现 Excel 转换 PDF

你知道的越多,你不知道的越多
点赞再看,养成习惯
如果您有疑问或者见解,欢迎指教:
企鹅:869192208

前言

最近遇到生成 Excel 并转 pdf 的需求,磕磕碰碰总结三种方式,分别是 POI + iText 库,EasyExce + iText 库和直接生成 PDF 表格三种方式。

本文基于 POI + iText 库实现

转换前后效果

转换前
转换后

引入 pom 配置
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>4.1.2</version>
</dependency>
<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.5.13</version>
</dependency>
代码实现
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Font;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Element;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.BaseColor;

@Slf4j
public class ExcelConvertService {

		public static void main(String[] args) throws Exception {
        poiAndItextPdf();
    }

		public static String getCellValue(Cell cell) {
        String cellValue = "";
        // 以下是判断数据的类型
        switch (cell.getCellTypeEnum()) {
            case NUMERIC: // 数字
                if (org.apache.poi.ss.usermodel.DateUtil.isCellDateFormatted(cell)) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    cellValue = sdf.format(org.apache.poi.ss.usermodel.DateUtil.getJavaDate(cell.getNumericCellValue())).toString();
                } else {
                    DataFormatter dataFormatter = new DataFormatter();
                    cellValue = dataFormatter.formatCellValue(cell);
                }
                break;
            case STRING: // 字符串
                cellValue = cell.getStringCellValue();
                break;
            case BOOLEAN: // Boolean
                cellValue = cell.getBooleanCellValue() + "";
                break;
            case FORMULA: // 公式
                cellValue = cell.getCellFormula() + "";
                break;
            case BLANK: // 空值
                cellValue = "";
                break;
            case ERROR: // 故障
                cellValue = "非法字符";
                break;
            default:
                cellValue = "未知类型";
                break;
        }
        return cellValue;
    }


    private static void poiAndItextPdf() throws Exception {
        try (Workbook workbook = WorkbookFactory.create(new File("C:\\Users\\ChenDW\\Desktop\\对账明细报告.xlsx"));
             FileOutputStream fos = new FileOutputStream("C:\\Users\\ChenDW\\Desktop\\对账明细报告.pdf")) {
            // 获取第一个工作表
            Sheet sheet = workbook.getSheetAt(0);

            // 创建PDF文档对象
            Document document = new Document(PageSize.A2, 50, 50, 50, 50);

            // 创建PDF输出流
            PdfWriter writer = PdfWriter.getInstance(document, fos);

            // 打开PDF文档
            document.open();

            // 创建PDF表格对象
            PdfPTable table = new PdfPTable(sheet.getRow(0).getLastCellNum());
            table.setHeaderRows(1);

            // 设置表格宽度
            table.setWidthPercentage(100);

            // 设置表格标题
            Paragraph title = new Paragraph(sheet.getSheetName(), new Font(BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED), 16, Font.BOLD));
            title.setAlignment(Element.ALIGN_CENTER);
            document.add(title);

            // 添加表格内容
            for (Row row : sheet) {
                for (Cell cell : row) {
                    PdfPCell pdfCell = new PdfPCell(new Paragraph(getCellValue(cell), new Font(BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED), 12)));
                    pdfCell.setBorderWidth(1f);
                    pdfCell.setBorderColor(BaseColor.BLACK);
                    pdfCell.setPadding(5f);
                    pdfCell.setHorizontalAlignment(Element.ALIGN_CENTER);
                    pdfCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
                    if (cell.getRowIndex() == 0) {
                        pdfCell.setBackgroundColor(BaseColor.LIGHT_GRAY);
                    }
                    table.addCell(pdfCell);
                }
            }

            // 添加表格到PDF文档
            table.setSpacingBefore(20f);
            table.setSpacingAfter(20f);
            table.setKeepTogether(true);
            document.add(table);

            // 关闭PDF文档
            document.close();
        } catch (IOException | DocumentException e) {
            e.printStackTrace();
        }
    }
}

至此,就基于 POI 和 iText 库实现了 Excel 转 PDF 的逻辑。

  • 10
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Excel是一种常用的办公软件,可以用来制作各类表格和图表。而PDF是一种便捷的文件格式,具有跨平台、可读性好等特点。因此,将Excel文件转换PDF格式,可以方便地与他人共享和阅读。下面是使用POIiTextPDFExcel文件转换PDF的步骤: 1. 导入POIiTextPDF。这两个可以通过在工程中引入相应的jar文件来实现。 2. 读取Excel文件并创建一个工作簿。使用POI的Workbook类可以读取和操作Excel文件。 3. 遍历Excel文件中的每一张表格,并将表格数据写入PDF文件中。使用POI的Sheet类和Row类来访问表格和行数据。 4. 创建一个PDF文档对象,并设置相关属性。使用iTextPDF的Document类可以创建PDF文档,并设置页面大小、标题和作者等属性。 5. 将Excel表格数据写入PDF文件中。通过遍历Excel表格中的单元格,并使用iTextPDF的Paragraph类将数据写入PDF文件。 6. 关闭文档对象,保存并关闭Excel文件。使用iTextPDFPdfWriter类将文档对象写入PDF文件,而使用POI的Workbook类可以保存并关闭Excel文件。 7. 完成转换,生成的PDF文件即可在设备上使用。 这就是使用POIiTextPDFExcel文件转换PDF的基本步骤。转换后的PDF文件可以方便地共享和阅读,方便管理和交流。这个方法非常适用于需要将大量Excel表格转换PDF文档的场景,如报表生成、数据分析等。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值