你知道的越多,你不知道的越多
点赞再看,养成习惯


文章目录

  • 前言
  • 转换前后效果
  • 引入 pom 配置
  • 代码实现


前言

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

本文基于 POI + iText 库实现

转换前后效果

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


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

引入 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 的逻辑。