2012-11-05

在 Spring MVC 3.1.2.RELEASE 產出 JasperReports 4.7.1 報表

本篇筆記接續 Hello JasperReports 4.7.1 with Spring MVC 3.1.2

前一篇筆記僅輸出標題,現在來輸出表身(Detail),官方文件為 17.7.3 Populating the ModelAndView

表身資料可以使用兩種資料類型:JRDataSource  與 Collection,如果只有一組資料要傳給 Jasper,那就直接放在 Model 裡就可以了。

@RequestMapping("/helloReport")
public String helloReport(Model model) {
  model.addAttribute("title", "This is a 標題...");

  // Map 表示一筆資料,再用 List 裝起來,表示所有資料
  Collection<Map<String, ?>> list = new ArrayList<Map<String, ?>>();
  // 塞入測試資料
  for (int i = 0; i < 10; i++) {
    Map<String, Object> data = new HashMap<String, Object>();
    data.put("id", new BigDecimal(i + 1));
    data.put("title", "中文 字串 String " + i);
    data.put("date", new Date(112, 9, i + 1));
    list.add(data);
  }
  // 可以直接使用 Collection 類型
  model.addAttribute("dataSource", list);

  // 也可以使用 JRDataSource 類型
  // model.addAttribute("dataSource", new JRMapCollectionDataSource(list));

  return "helloReport";
} 

如果有多組資料,那就得另外指定。
@RequestMapping("/helloReport")
public String helloReport(Model model) {
  model.addAttribute("title", "This is a 標題...");

  // ...

  model.addAttribute("dataSource1", dataSource1);
  model.addAttribute("dataSource1", dataSource2);

  return "helloReport";
}
傳給 Jasper 兩組 JRDataSource,所以得在 ResourceBundleViewResolver 的 views.properties 裡使用 reportDataKey 指定要使用哪一組 JRDataSource。---
helloReport.(class)=org.springframework.web.servlet.view.jasperreports.JasperReportsPdfView
helloReport.url=/WEB-INF/reports/helloReport.jasper
helloReport.reportDataKey=dataSource2
至於報表怎麼拉,請參考 使用 Java 輸出資料到 JasperReports 主報表表身(Detail)

收工。
---
---
---

沒有留言:

張貼留言