Excel转PDF较好实践
直接上代码,暂时是较为粗糙的版本,采用的类库是POI3.13,iText7.0
public class Excel2PDFUtil { public static void main(String[] args) throws Exception { FileInputStream input_document = new FileInputStream(new File("C:" + File.separator + "Users" + File.separator + "Administrator" + File.separator + "Desktop" + File.separator + "test2016052004.xls")); // Read workbook into HSSFWorkbook HSSFWorkbook my_xls_workbook = new HSSFWorkbook(input_document); // Read worksheet into HSSFSheet HSSFSheet my_worksheet = my_xls_workbook.getSheetAt(0); // To iterate over the rows Iterator<Row> rowIterator = my_worksheet.rowIterator(); // We will create output PDF document objects at this point Document iText_xls_2_pdf = new Document(); PdfWriter.getInstance(iText_xls_2_pdf, new FileOutputStream("C:" + File.separator + "Users" + File.separator + "Administrator" + File.separator + "Desktop" + File.separator + "Excel2PDF_Output.pdf")); iText_xls_2_pdf.open(); Font font = new Font(BaseFont.createFont("C:/Windows/Fonts/SIMYOU.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED)); // we have two columns in the Excel sheet, so we create a PDF table with // two columns // Note: There are ways to make this dynamic in nature, if you want to. PdfPTable my_table = new PdfPTable(60); // We will use the object below to dynamically add new data to the table PdfPCell table_cell; PdfPRow table_row; // Loop through rows. while (rowIterator.hasNext()) { Row row = rowIterator.next(); Iterator<Cell> cellIterator = row.cellIterator(); while (cellIterator.hasNext()) { Cell cell1 = cellIterator.next(); // Fetch CELL switch (cell1.getCellType()) { // Identify CELL type // you need to add more code here based on // your requirement / transformations case Cell.CELL_TYPE_STRING: // Push the data from Excel to PDF Cell //table_cell = new PdfPCell(new Phrase(cell1.getStringCellValue())); // feel free to move the code below to suit to your needs my_table.addCell(new Paragraph(cell1.getStringCellValue(), font)); break; case Cell.CELL_TYPE_NUMERIC: //table_cell = new PdfPCell(new Phrase(new Double(cell1.getNumericCellValue()).floatValue())); my_table.addCell(new Paragraph(String.valueOf(cell1.getNumericCellValue()), font)); break; case Cell.CELL_TYPE_BLANK: //table_cell = new PdfPCell(new Phrase("")); my_table.addCell(new Paragraph("", font)); break; default: throw new Exception("出现了未预知的单元格格式"); } // next line } } // Finally add the table to PDF document iText_xls_2_pdf.add(my_table); iText_xls_2_pdf.close(); // we created our pdf file.. my_xls_workbook.close();// close workbook input_document.close(); // close xls } }
浙公网安备 33010602011771号