Java Implementation of PDF and Excel Export with Dynamic Data Insertion
This article provides a step‑by‑step Java tutorial for generating PDF and Excel files, dynamically inserting data from backend entities, and exporting them, including detailed configuration, code examples using iText and EasyExcel, and testing procedures.
1. Introduction
Exporting data to PDF and Excel is a common requirement in enterprise applications; this guide records a complete solution for handling both formats in Java.
2. Business Requirements
Generate a PDF form from a template and allow users to download it.
Export queried data as an Excel spreadsheet.
3. PDF Generation
Step 1: Create PDF Template
Design the form in Word, save as PDF, and use Adobe Acrobat DC to convert it into a fillable form.
Step 2: Code Implementation
Import the iText dependency and write a controller method that reads the PDF template, fills fields with data from a Java bean, and streams the result to the client.
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13</version>
</dependency>
@RegisterToSMP(serviceDisplay = "预览页面PDF下载")
@RequestMapping(value = "/DM/gwclwxsq/qygl/exportPDF$m=query.service", method = RequestMethod.POST)
public String exportPdf(@RequestBody GwclwxsqBean gwclwxsqBean, HttpServletResponse response) throws UnsupportedEncodingException {
System.setProperty("javax.xml.parsers.DocumentBuilderFactory", "com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl");
String filename = "车辆维修审批单.pdf";
String path = "e:/";
response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(filename, "UTF-8"));
OutputStream os = null;
PdfStamper ps = null;
PdfReader reader = null;
try {
os = response.getOutputStream();
reader = new PdfReader(path + "/" + filename);
ps = new PdfStamper(reader, os);
AcroFields form = ps.getAcroFields();
BaseFont bf = BaseFont.createFont("C:/WINDOWS/Fonts/SIMSUN.TTC,1", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
form.addSubstitutionFont(bf);
Map
data = new HashMap<>();
data.put("commitTime", gwclwxsqBean.getCommitTime());
// ... other fields ...
for (String key : data.keySet()) {
form.setField(key, data.get(key).toString());
}
ps.setFormFlattening(true);
log.info("*******************PDF导出成功***********************");
} catch (Exception e) {
log.error("*******************PDF导出失败***********************");
e.printStackTrace();
} finally {
try { ps.close(); reader.close(); os.close(); } catch (Exception e) { e.printStackTrace(); }
}
return null;
}Testing
After deploying, the PDF generation and download work as expected (screenshots omitted).
4. Excel Generation
Using EasyExcel, the tutorial shows how to map a data bean to an Excel file, write the file, and stream it to the client.
import lombok.Data;
@Data
public class ExportYqfkdj {
private Integer xuhao;
private String xingming;
private String zjhm;
private String lxdh;
private String sqrGzdw;
private String sfjcgysbl;
private String sfyjjglrytz;
private String dqzt;
private String dqjkzt;
private String dqtw;
private String dqszdz;
private String dqjzdz;
private String tjsj;
} @Transactional(rollbackFor = { Exception.class })
public DataResult exporYqfkdj(YqfkdjBean yqfkdjBean) throws Exception {
// query data, build list, generate file path
EasyExcel.write(filepath, ExportYqfkdj.class).head(head()).sheet().doWrite(list);
// set result and return
} @RegisterToSMP(serviceDisplay = "疫情防控查询导出")
@RequestMapping(value = "/DM/yqfkdj/gr/yqfkdjdc$m=export.service", method = RequestMethod.POST)
public void exportKhfxxx(@RequestBody YqfkdjBean yqfkdjBean, HttpServletResponse resp) throws Exception {
DataResult result = yqfkdjService.exporYqfkdj(yqfkdjBean);
String filepath = result.getMsg().replace("\"", "");
File file = new File(filepath);
// stream file to response
}Testing confirms that both PDF and Excel files are generated, populated with data, and downloadable.
Source: cnblogs.com/Tom-shushu/p/14279357.html
Selected Java Interview Questions
A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.