java实现excel转pdf

本文介绍如何使用Java将Excel数据转换为PDF格式,涉及itextpdf和Apache POI库的使用,详细展示了代码实现过程。

基本原理

将excel单元格的值读取出来,然后生成一份pdf,并将单元格数据写进去。

用到的库

		<!-- 写入pdf用的库 -->
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.5.13</version>
        </dependency>

        <!-- 让PDF支持中文写入 -->
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itext-asian</artifactId>
            <version>5.2.0</version>
        </dependency>


        <!-- 操作excel的库 -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>4.0.0</version>
        </dependency>

具体操作

package com.example.demo;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Iterator;



public class DemoApplication {

    public static void main(String[] args) throws Exception{
    	//excel文件路径
        String excelFile = "C:\\Users\\admin\\Desktop\\source1.xls";
        //pdf文件输出路径
        String out = "C:\\Users\\admin\\Desktop\\out.pdf";

        //设置中文
        BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",
                BaseFont.NOT_EMBEDDED);
        //普通字体
        Font fontChinese = new Font(bfChinese, 12, Font.NORMAL);
     

		//读取excel
        FileInputStream input_document = new FileInputStream(new File(excelFile));
        HSSFWorkbook my_xls_workbook = new HSSFWorkbook(input_document);
        HSSFSheet my_worksheet = my_xls_workbook.getSheetAt(0);
        //获取excel总列数
        int totalCol = my_worksheet.getRow(0).getPhysicalNumberOfCells();
        //准备遍历excel 
        Iterator<Row> rowIterator = my_worksheet.iterator();

        //生成一个pdf
        Document iText_xls_2_pdf = new Document();
        PdfWriter.getInstance(iText_xls_2_pdf, new FileOutputStream(out));
        iText_xls_2_pdf.open();
        //在pdf中创建一个表格
        PdfPTable my_table = new PdfPTable(totalCol);
        
  		//遍历excel, 将数据输出到pdf的表格中
        PdfPCell table_cell = null;
        while(rowIterator.hasNext()) {
            Row row = rowIterator.next();
            Iterator<Cell> cellIterator = row.cellIterator();
            while(cellIterator.hasNext()) {
                Cell cell = cellIterator.next(); //Fetch CELL
                if(cell.getCellType() == CellType.STRING){
                    //Push the data from Excel to PDF Cell
                    table_cell=new PdfPCell(new Phrase(cell.getStringCellValue(), usedFont));
                }
                if(cell.getCellType() == CellType.NUMERIC){
                    //Push the data from Excel to PDF Cell
                    table_cell=new PdfPCell(new Phrase(String.valueOf(cell.getNumericCellValue()), usedFont));
                }
                my_table.addCell(table_cell);
            }
        }
        iText_xls_2_pdf.add(my_table);
        iText_xls_2_pdf.close();
        input_document.close(); //close xls
    }

}

### Java 实现 Excel PDF 方法 在 Java 中,可以使用多种第三方库来实现Excel 文件转换PDF 的功能。以下是几种常见的方法及其对应的库。 #### 方法一:Aspose.Cells Aspose.Cells 是一个强大的商业库,支持处理各种电子表格操作,包括将 Excel 文件转换PDF 格式。其主要优点在于无需依赖 Microsoft Office 即可完成转换过程[^3]。 ```java import com.aspose.cells.*; public class ExcelToPdfConverter { public static void main(String[] args) throws Exception { // 加载Excel文件 Workbook workbook = new Workbook("input.xlsx"); // 设置PDF保存选项 PdfSaveOptions options = new PdfSaveOptions(); // 保存为PDF格式 workbook.save("output.pdf", options); } } ``` 上述代码展示了如何通过 Aspose.Cells 库加载 Excel 文件并将其保存为 PDF 格式的具体实现方式[^3]。 --- #### 方法二:Apache POI 和 iText 结合 虽然 Apache POI 不直接提供将 Excel 转换PDF 的功能,但它可以帮助读取 Excel 数据。随后可以通过 iText 或其他类似的 PDF 处理工具生成 PDF 文档[^1]。 ```java import org.apache.poi.ss.usermodel.*; import com.itextpdf.text.Document; import com.itextpdf.text.Paragraph; import com.itextpdf.text.pdf.PdfWriter; import java.io.FileInputStream; import java.util.Iterator; public class PoiItExtExample { public static void main(String[] args) throws Exception { FileInputStream fileInputStream = new FileInputStream("input.xlsx"); Workbook workbook = WorkbookFactory.create(fileInputStream); Document document = new Document(); PdfWriter.getInstance(document, new FileOutputStream("output.pdf")); document.open(); Sheet sheet = workbook.getSheetAt(0); Iterator<Row> rowIterator = sheet.iterator(); while (rowIterator.hasNext()) { Row row = rowIterator.next(); StringBuilder rowData = new StringBuilder(); for (int cellIndex = 0; cellIndex < row.getLastCellNum(); cellIndex++) { Cell cell = row.getCell(cellIndex); if (cell != null) { rowData.append(cell.toString()).append("\t"); } else { rowData.append("").append("\t"); } } Paragraph paragraph = new Paragraph(rowData.toString()); document.add(paragraph); } document.close(); fileInputStream.close(); } } ``` 此代码片段说明了如何利用 Apache POI 提取 Excel 数据并通过 iText 创建 PDF 文件的过程。 --- #### 方法三:JODConverter(基于 LibreOffice) JODConverter 可以作为桥梁连接到 LibreOffice/OpenOffice 并执行文档之间的相互转换任务。它能够轻松地把 Excel 表格化为 PDF 文件[^2]。 ```java import org.jodconverter.LocalConverter; import org.jodconverter.office.OfficeManager; import org.jodconverter.office.LocalOfficeManager; public class JodConvertExample { public static void main(String[] args) { try (OfficeManager officeManager = LocalOfficeManager.builder().buildAndStart()) { LocalConverter.make(officeManager) .convert(new File("input.xlsx")) .to(new File("output.pdf")) .execute(); } catch (Exception e) { e.printStackTrace(); } } } ``` 该部分描述的是借助 JODConverter 工具配合本地安装的 LibreOffice 来达成从 ExcelPDF变流程[^2]。 --- ### 总结 以上介绍了三种不同的技术方案用于解决 Java 编程环境下由 ExcelPDF 进行化的需求。每种都有各自的特点以及适用场景: - **Aspose.Cells**: 商业化产品,易于集成且性能优越; - **Apache POI + iText**: 开源组合,灵活性高但开发成本较大; - **JODConverter**: 借助外部软件服务端口,适合批量自动化作业环境。 选择合适的解决方案取决于项目预算、时间安排和技术偏好等因素。 问题
评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值