之前一直用破解版aspose.cell来着,但是转换出来效果不理想,贼拉难看,加上项目中有用到itext,就开始找利用itext转换excel的方法,然后就找到了个借助poi写入itextPdf的思路,尝试了下,效果还不错,记录一下。
itext版本: 7.1.11
public static void excelToPdf(String inFilePath, String outFilePath) {
PdfFont pdfFont = PdfFontFactory.createFont("STSong-Light", "UniGB-UCS2-H", true);
try (PdfDocument pdf = new PdfDocument(new PdfWriter(new FileOutputStream(outFilePath)));
Document document = new Document(pdf, PageSize.A4.rotate());) {
String type = "xls".equals(getSuffix(inFilePath).trim()) ?
"org.apache.poi.hssf.usermodel.HSSFWorkbook" : "org.apache.poi.xssf.usermodel.XSSFWorkbook";
// 文件输入流读取文件
InputStream in = new FileInputStream(inFilePath);
// 反射创建workbook
Class workbookClass = Class.forName(type);
org.apache.poi.ss.usermodel.Workbook workbook = (org.apache.poi.ss.usermodel.Workbook) workbookClass.getConstructor(InputStream.class).newInstance(in);
Sheet sheet = workbook.getSheetAt(0);
int column = sheet.getRow(0).getLastCellNum();
int row = sheet.getPhysicalNumberOfRows();
Table table = new Table(column - sheet.getRow(0).getFirstCellNum());
String str = null;
for (int i = sheet.getFirstRowNum(); i < row; i++) {
for (int j = sheet.getRow(0).getFirstCellNum(); j < column; j++) {
//获取excel单元格
org.apache.poi.ss.usermodel.Cell cell = sheet.getRow(i).getCell(j);
if (cell.getCellType() == CellType.NUMERIC) {
str = (int) cell.getNumericCellValue() + "";
} else {
str = cell.getStringCellValue();
}
Cell cells = new Cell().setFont(pdfFont).add(new Paragraph(str));
table.addCell(cells);
}
}
document.add(table);
} catch (Exception e) {
throw new CustomException(ResponseEnum.FILE_CONVERT_FAILED, Locale.ENGLISH);
}
}
private static String getSuffix(String filePath) {
int dotIndex = filePath.lastIndexOf(".");
return filePath.substring(dotIndex + 1);
}