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


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

    前言

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

    本文基于 POI + iText 库实现

    转换前后效果

    转换前
    转换后

    引入 pom 配置
    <dependency>
        <groupId>org.apache.poigroupId>
        <artifactId>poiartifactId>
        <version>4.1.2version>
    dependency>
    <dependency>
        <groupId>com.itextpdfgroupId>
        <artifactId>itextpdfartifactId>
        <version>5.5.13version>
    dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    代码实现
    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();
            }
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119

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

  • 相关阅读:
    spark相关网站
    在vue2和vue3中Vuex的使用及其持久化存储,mutation和actions的区别
    Docker 搭建 Minio 容器 (完整详细版)
    【AtomicLong】常规用法
    C++类构造函数和析构函数
    群晖7.2版本安装CloudDriver2(套件)挂载alist(xiaoya)到本地
    机器学习笔记之高斯混合模型(三)EM算法求解高斯混合模型(E步操作)
    Java开发自学教程!这里有份超全Java体系化进阶学习图谱
    在Ubuntu 18.04安装Docker
    Nginx之sticky第三方模块使用解读
  • 原文地址:https://blog.csdn.net/CDWLX/article/details/136311199