In actual development, we often encounter the need to convert Excel files into PDF files. Java provides a variety of libraries and tools to implement this function. Below I will introduce you to a common implementation method, using Apache POI to read Excel files, and then using iText to generate PDF files.
1. Introduce the required libraries
First, we need to introduce Apache POI and iText-related libraries into our project. If you are using a Maven project, add the following dependencies to the file:
<!-- Apache POI Used for reading Excel document --> <dependency> <groupId></groupId> <artifactId>poi</artifactId> <version>5.2.3</version> </dependency> <dependency> <groupId></groupId> <artifactId>poi-ooxml</artifactId> <version>5.2.3</version> </dependency> <!-- iText Used for generation PDF document --> <dependency> <groupId></groupId> <artifactId>itextpdf</artifactId> <version>5.5.13.3</version> </dependency>
2. Code to implement Excel to PDF
Here are specific Java code examples:
import .*; import ; import ; import ; import .*; import ; import .*; public class ExcelToPdfConverter { public static void main(String[] args) { try { // Read Excel files FileInputStream excelFile = new FileInputStream(""); Workbook workbook = new XSSFWorkbook(excelFile); Sheet sheet = (0); // Create PDF document Document document = new Document(); (document, new FileOutputStream("")); (); // Create a PDF table with the same number of columns as the Excel table int columnCount = (0).getLastCellNum(); PdfPTable pdfTable = new PdfPTable(columnCount); // traverse every row of an Excel table for (Row row : sheet) { // Iterate through each cell of the current row for (Cell cell : row) { // Get the value of the cell String cellValue = getCellValueAsString(cell); // Create a cell for a PDF table PdfPCell pdfCell = new PdfPCell(new Phrase(cellValue)); // Add cells to PDF table (pdfCell); } } // Add PDF table to PDF document (pdfTable); // Close the document and Excel file (); (); (); ("Excel to PDF successfully!"); } catch (Exception e) { (); ("Excel failed to convert PDF:" + ()); } } // Convert the value of the cell to a string private static String getCellValueAsString(Cell cell) { if (cell == null) { return ""; } switch (()) { case STRING: return (); case NUMERIC: if ((cell)) { return ().toString(); } else { return (()); } case BOOLEAN: return (()); case FORMULA: return (); default: return ""; } } }
3. Detailed explanation of the code
1. Read Excel file:
- FileInputStream excelFile = new FileInputStream("");: Create a FileInputStream object to read files.
- Workbook workbook = new XSSFWorkbook(excelFile);: Use the XSSFWorkbook class to create a Workbook object to represent an Excel file.
- Sheet sheet = (0);: Get the first worksheet of the Excel file.
2. Create PDF document:
- Document document = new Document();: Creates a Document object to represent a PDF document.
- (document, new FileOutputStream(""));: Use PdfWriter to associate the Document object with FileOutputStream, specifying the generated PDF file name as .
- ();: Open the PDF document and prepare to write the content.
3. Create PDF table:
- int columnCount = (0).getLastCellNum();: Get the number of columns in the first row of the Excel table.
- PdfPTable pdfTable = new PdfPTable(columnCount);: Create a PdfPTable object to represent a PDF table with the same number of columns as the number of columns in an Excel table.
4. Traverse Excel table and fill in PDF table:
- for (Row row : sheet) {... }: traverses every row of an Excel table.
- for (Cell cell : row) {... }: Iterates through each cell of the current row.
- String cellValue = getCellValueAsString(cell);: Call the getCellValueAsString method to convert the value of the cell into a string.
- PdfPCell pdfCell = new PdfPCell(new Phrase(cellValue));: Creates a PdfPCell object to represent cells of a PDF table.
- (pdfCell);: Add a PdfPCell object to the PdfPTable.
5. Add a PDF table to a PDF document:
(pdfTable);: Add a PdfPTable object to the Document.
6. Close the document and Excel file:
(); (); (); ();: Close PDF documents, Excel files, and input streams, and free resources.
4. Things to note
The above code only processes the first worksheet in an Excel file. If you need to process multiple worksheets, you can use the () method to get the number of worksheets and then iterate through each worksheet for processing.
The getCellValueAsString method in the code is used to convert cell values of different types into strings, ensuring that no exceptions appear when handling cells of different types.
This is the end of this article about using Java to implement Excel to PDF. For more related Java Excel to PDF content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!