From:http://hi.baidu.com/lxiangshanyu/blog/item/171a7661a5ce53720d33fa76.html
Model类:
主表对应Model类:
public class OrderIreport {
private Long id;
private String orderSN;
private String email;
private String tel;
private String status;
private String memo;
private String creator;
private List<OrderInfoIreport> orderInfos;
//Set、Get方法省略
}
子表对应的Model类:
public class OrderInfoIreport {
private Long id;
private String orderSN;
private int num;
private Timestamp startDate;
private Timestamp endDate;
//Set、Get方法省略
}
Struts:Action方法
public String print() throws JRException, IOException{
//数据源
orders = orderManagers.getAllOrder();
if(orders != null && !(orders.isEmpty())){
for(int i = 0;i < orders.size();i++){
List<OrderInfoIreport> orderInfo = orderManagers.getOrderInfoByOrderSN(orders.get(i).getOrderSN());
orders.get(i).setOrderInfos(orderInfo);
}
}
ServletContext context = getRequest().getSession().getServletContext();
String subPath = context.getRealPath("/reports/OrderSub.jasper"); //OrderSub.jasper 子报表
String filePath = context.getRealPath("/reports/OrderPrint.jasper"); //OrderPrint.jasper 主报表
JasperReport subReport = (JasperReport)JRLoader.loadObject(subPath);
JasperReport fileReport = (JasperReport)JRLoader.loadObject(filePath);
Map subMap = new HashMap();
subMap.put("SUBREPORT_DIR", subReport); //子报表路径
JRBeanCollectionDataSource dataSource =new JRBeanCollectionDataSource(orders);
JasperPrint jasperPrint = JasperFillManager.fillReport(fileReport, subMap, dataSource);
HttpServletResponse response = ServletActionContext.getResponse();
OutputStream os = response.getOutputStream();
response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "filename=orderPrint.pdf");
response.setCharacterEncoding("UTF-8");
JRPdfExporter exporter = new JRPdfExporter();
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, os);
exporter.exportReport();
return null;
}
在做struts2整合ireport复合报表时最重要的是子报表的路径和子报表的数据源。
1)子报表的路径是由SUBREPORT_DIR变量指明的,程序中已标明,主报表是根据SUBREPORT_DIR变量找到子报表的;
2)子报表的数据源:子报表的数据源也是由主报表提供的,在主报表中增加 orderInfos(主表对应的Model类中的属性) 字段,然后在主报表中双击子报表,选择子报表标签,连接/数据源表达式 选择使用数据源表达式,表达式为new net.sf.jasperreports.engine.data.JRBeanCollectionDataSource($F{orderInfos});在 子报表(其他) 标签中,子报表表达式类选择 net.sf.jasperreports.engine,JasperReport ,子报表表达式为 $P{SUBREPORT_DIR}
创建子报表时就跟创建一张普通的报表一样,没有特殊的设置
最后,在Action中的return返回时返回NULL即可