Java jasper报告列表作为数据源

时间:2010-10-18 10:26:25

标签: java jasper-reports

我想将列表对象作为我的数据源,你能告诉我.jrxml文件我应该如何设计我的报告?

public class TestReport 
{
 public void runReport(String fileName, String outFileName) 
 {
  try 
  {
   List<R> list = new ArrayList<R>(5);

   Map parameters = new HashMap();
   list.add(new R("a1" ,"a2"));
   list.add(new R("b1" ,"b2"));
   list.add(new R("c1" ,"c2"));
     /*parameters.put("my_name", "faisal khan");
     parameters.put("my_addr", "address comes here");*/
            JasperPrint print = JasperFillManager.fillReport( fileName, parameters, new JREmptyDataSource());
            JRExporter exporter = new JRPdfExporter();
            exporter.setParameter(
            JRExporterParameter.OUTPUT_FILE_NAME,outFileName);
            exporter.setParameter(
            JRExporterParameter.JASPER_PRINT, print);
            JasperExportManager.exportReportToPdfFile(print, outFileName);
            print = null;
            exporter = null;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

 private class R{
  private String name;
  private String addr;

  public R(String name, String addr) {
   super();
   this.name = name;
   this.addr = addr;
  }
  public String getName() {
   return name;
  }
  public void setName(String name) {
   this.name = name;
  }
  public String getAddr() {
   return addr;
  }
  public void setAddr(String addr) {
   this.addr = addr;
  }

 }
  public static void main(String args[]){
   new TestReport().runReport("/home/faisalloe/ireports/report1.jasper", "/home/faisalloe/ireports/report1.pdf");
  }
}

1 个答案:

答案 0 :(得分:8)

对集合使用JasperDatasource:net.sf.jasperreports.engine.data.JRBeanCollectionDataSource

JasperPrint print = JasperFillManager.fillReport( fileName, parameters, new JRBeanCollectionDataSource(list));

您的报告将针对每个元素重复一次。或者,您可以根据主报告定义子报表,每个列表元素重复一次。