利用Java反射实现通用的Excel报表

本文介绍了一种用于创建Excel报表的通用代码实现方法。该方法能够根据提供的数据和标题映射自动生成Excel文件,适用于批量生成报表场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近有很多客户报表需要提供客户下载,需要生成一个Excel的格式文件,所以写了
一个通用的Excel报表生成代码供各个地方使用:

public <T> void createExcelReport(List<T> reports,Map<String,String> headerMap,OutputStream output) throws IOException {
if(reports == null || reports.isEmpty()) return;

Workbook wb = new HSSFWorkbook();
HSSFSheet sheet = (HSSFSheet) wb.createSheet("报表");
HSSFRow row = sheet.createRow(0);

//create header
Object report = reports.get(0);
Field[] fields = report.getClass().getDeclaredFields();
for(int i = 0; i < fields.length; i++){
String headValue = headerMap.get(fields[i].getName());
row.createCell(i).setCellValue(headValue);
sheet.setColumnWidth(i, 20 * 256);
}

//fill the data
for(int i = 0; i < reports.size(); i++){
Object rp = reports.get(i);
row = sheet.createRow(i+1);
for(int j = 0; j < fields.length; j++){
String getMethodName = "get" + StringUtils.capitalize(fields[j].getName());
Method method = null;
try {
method = rp.getClass().getMethod(getMethodName, null);
}catch(NoSuchMethodException e){//for boolean type isField
getMethodName = "is" + StringUtils.capitalize(fields[j].getName());
try {
method = rp.getClass().getMethod(getMethodName, null);
} catch (Exception ex){
throw new RuntimeException("Create Report failed!",ex);
}
}
if(method != null){
Object value;
try {
value = method.invoke(rp);
value = value == null ? "" : value;
row.createCell(j).setCellValue(value.toString());
} catch (Exception e) {
throw new RuntimeException("Create Report failed!",e);
}
}
}
}
wb.write(output);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值