你知道的越多,你不知道的越多
点赞再看,养成习惯
如果您有疑问或者见解,欢迎指教:
企鹅:869192208
文章目录
- 前言
- 转换前后效果
- 引入 pom 配置
- 代码实现
前言
最近遇到生成 Excel 并转 pdf 的需求,磕磕碰碰总结三种方式,分别是 POI + iText 库,EasyExce + iText 库和直接生成 PDF 表格三种方式。
本文基于 POI + iText 库实现
转换前后效果
引入 pom 配置
<dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>4.1.2</version>
</dependency>
<dependency><groupId>com.itextpdf</groupId><artifactId>itextpdf</artifactId><version>5.5.13</version>
代码实现
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: // BooleancellValue = 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();}}
}
至此,就基于 POI 和 iText 库实现了 excel 转 pdf 的逻辑。