开篇互动:你的项目是否还在手动导出数据?
“每天手动导出表格、打印报告是否让你抓狂?”
如果你还在为数据的可视化和导出问题头疼,这篇文章将彻底解决你的困扰!从Excel到PDF,从基础操作到复杂场景,我们将用10+实战案例和万字长文手把手教你搞定一切!
一、为什么Java项目离不开Excel和PDF生成?
在企业级应用中,数据可视化和导出功能几乎是刚需:
- Excel导出:用于数据分析、报表生成、数据迁移等场景(如财务报表、销售统计)。
- PDF生成:适用于法律文件、合同签署、打印报告等场景(如简历生成、订单确认书)。
痛点总结:
- 手动实现表格布局费时费力
- 复杂格式(如图片插入、表格合并)难以处理
- 性能瓶颈:大数据量导出会卡顿
二、Excel生成:从零到精通
2.1 快速上手:JXL库实现基础功能
2.1.1 环境准备
<!-- pom.xml 添加依赖 -->
<dependency>
<groupId>net.sourceforge.jexcelapi</groupId>
<artifactId>jxl</artifactId>
<version>2.6.12</version>
</dependency>
2.1.2 创建并导出Excel文件
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import java.io.File;
public class ExcelGenerator {
public static void main(String[] args) {
try {
// 创建工作簿
WritableWorkbook workbook = Workbook.createWorkbook(new File("output.xls"));
WritableSheet sheet = workbook.createSheet("Sheet1", 0);
// 写入数据
sheet.addCell(new Label(0, 0, "姓名"));
sheet.addCell(new Label(1, 0, "年龄"));
sheet.addCell(new Label(2, 0, "邮箱"));
sheet.addCell(new Label(0, 1, "张三"));
sheet.addCell(new Label(1, 1, "28"));
sheet.addCell(new Label(2, 1, "zhangsan@example.com"));
// 保存并关闭
workbook.write();
workbook.close();
System.out.println("Excel 文件已生成!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
2.1.3 实战案例:复杂表格布局
// 合并单元格
sheet.mergeCells(0, 0, 2, 0); // 合并第0行第0列到第0行第2列
sheet.addCell(new Label(0, 0, "学生信息表", CellFormat.DEFAULT));
// 设置字体样式
WritableFont font = new WritableFont(WritableFont.ARIAL, 12, WritableFont.BOLD);
WritableCellFormat format = new WritableCellFormat(font);
sheet.addCell(new Label(0, 1, "姓名", format));
2.2 高阶操作:Apache POI实现复杂功能
2.2.1 POI简介与环境准备
POI是Apache提供的强大办公文档处理工具,支持Excel、Word、PPT等多种格式。
<!-- pom.xml 添加依赖 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>5.2.3</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.2.3</version>
</dependency>
2.2.2 创建并导出Excel文件
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileOutputStream;
import java.io.IOException;
public class POIExcelGenerator {
public static void main(String[] args) throws IOException {
// 创建工作簿
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet(" 学生信息");
// 创建标题行
Row headerRow = sheet.createRow(0);
headerRow.createCell(0).setCellValue(" 姓名");
headerRow.createCell(1).setCellValue(" 年龄");
headerRow.createCell(2).setCellValue(" 邮箱");
// 插入数据行
Row dataRow = sheet.createRow(1);
dataRow.createCell(0).setCellValue(" 李四");
dataRow.createCell(1).setCellValue(30);
dataRow.createCell(2).setCellValue("lisi@example.com");
// 自动调整列宽
for (int i = 0; i < 3; i++) {
sheet.autoSizeColumn(i);
}
// 保存文件
try (FileOutputStream outputStream = new FileOutputStream("output.xlsx")) {
workbook.write(outputStream);
workbook.close();
System.out.println("Excel 文件已生成!");
}
}
}
2.2.3 PDF生成:复杂表格布局与图片插入
// 插入图片
Drawing drawing = sheet.createDrawingPatriarch();
ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 1, 5, 4, 8);
Picture picture = drawing.createPicture(anchor, workbook.addPicture(new FileInputStream("logo.png"), Workbook.PICTURE_TYPE_PNG));
三、PDF生成:从零到实战
3.1 快速上手:iText库实现基础功能
3.1.1 环境准备
<!-- pom.xml 添加依赖 -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13.2</version>
</dependency>
3.1.2 创建并导出PDF文件
import com.itextpdf.text.Document;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.FileOutputStream;
import java.io.IOException;
public class PDFGenerator {
public static void main(String[] args) throws IOException {
// 创建文档
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream("output.pdf"));
document.open();
// 添加内容
document.add(new Paragraph("Hello World!"));
document.add(new Paragraph("这是一份由Java生成的PDF文件!"));
// 关闭文档
document.close();
System.out.println("PDF 文件已生成!");
}
}
3.1.3 实战案例:复杂表格布局
import com.itextpdf.text.pdf.PdfPTable;
// 创建表格
PdfPTable table = new PdfPTable(3);
table.addCell(" 姓名");
table.addCell(" 年龄");
table.addCell(" 邮箱");
table.addCell(" 王五");
table.addCell("25");
table.addCell("wangwu@example.com");
document.add(table);
3.2 高阶操作:PDFBox实现复杂功能
3.2.1 PDFBox简介与环境准备
PDFBox是Apache提供的PDF处理工具,支持PDF的生成、修改和解析。
<!-- pom.xml 添加依赖 -->
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.24</version>
</dependency>
3.2.2 创建并导出PDF文件
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import java.io.IOException;
public class PDFBoxGenerator {
public static void main(String[] args) throws IOException {
// 创建文档
PDDocument document = new PDDocument();
PDPage page = new PDPage();
document.addPage(page);
// 创建内容流
PDPageContentStream contentStream = new PDPageContentStream(document, page);
// 设置字体和颜色
contentStream.setFont(PDType1Font.HELVETICA_BOLD, 18);
contentStream.setNonStrokingColor(Color.BLACK);
// 添加文本
contentStream.beginText();
contentStream.newLineAtOffset(100, 700);
contentStream.showText("Hello World!");
contentStream.endText();
// 关闭内容流和文档
contentStream.close();
document.save("output.pdf");
document.close();
}
}
3.2.3 PDF合并与水印添加
// 合并PDF文件
PDDocument mergedDoc = PDDocument.load(new File("file1.pdf"));
mergedDoc.importPages(PDDocument.load(new File("file2.pdf")).getPages(), null, true);
mergedDoc.save("merged.pdf");
// 添加水印
contentStream.beginText();
contentStream.setNonStrokingColor(Color.LIGHT_GRAY);
contentStream.setFont(PDType1Font.HELVETICA, 40);
contentStream.setTextRotation(45);
contentStream.setTextAlignment(PDPageContentStream.TextAlignment.CENTER);
contentStream.newLineAtOffset(page.getMediaBox().getWidth() / 2, page.getMediaBox().getHeight() / 2);
contentStream.showText("Watermark");
contentStream.endText();
四、常见问题与解决方案
4.1 Excel导出性能优化
- 使用内存流代替文件流(减少磁盘IO)
- 合理设置单元格样式(避免重复创建)
4.2 PDF生成常见问题
- 中文乱码:引入iTextAsian扩展包支持中文字体
- 图片插入失败:检查图片路径和格式是否正确
4.3 数据绑定与动态生成
- 使用数据库查询结果动态填充表格内容
- 结合模板引擎(如Velocity)实现复杂布局
五、结语与互动
亲爱的读者朋友们!
通过这篇文章,你已经掌握了Java生成Excel和PDF的核心技能。如果你有任何疑问或想看到更多实战案例,请在评论区留言!我会逐一回复并分享更多技巧。