天天看點

快速學習JasperReport-資料填充

1 資料填充

我們介紹了如何使用JasperReport來生成簡單的文本報表,正式企業開發中動态資料展示也是報表中最重要的一環,接下來我們共同研究的就是填充動态資料到PDF報表中。

/**
* 填充資料構造JasperPrint
* is: 檔案輸入流
* parameters:參數
* dataSource:資料源
*/
public static JasperPrint fillReport(InputStream is, Map<String, Object> parameters, JRDataSource dataSource) throws JRException {      

通過這段填充資料的源代碼得知,JasperReport對報表模闆中的資料填充有很多中方式,最典型的有以下兩種:

  1. Parameters(參數)填充
  2. DataSource(資料源)填充

1.1 參數Map填充資料

Parameters通常是用來在列印的時候從程式裡傳值到報表裡。也就是說parameters通常的是起參數傳遞的作用。他們可以被用在一些特定的場合(比如應用中SQL 查詢的條件),如report中任何一個需要從外部傳入的變量等(如一個Image對象所包括的char或報表title的字元串)。parameters也需要在建立的時候定義它的資料類型。parameters的資料類型是标準的java的Object。

1.1.1 模闆制作

(1) 建立新模闆,删除不需要的Band

快速學習JasperReport-資料填充

(2)建立Parameter

在outline面闆中找到Parameters,右鍵 -> Create Parameter,建立一個Parameter(生成一個Paramerter1)

快速學習JasperReport-資料填充

右鍵 Paramete1 -> Show Properties. 設定Name為title、Class為java.lang.String.這裡要注意名字要認真取不能重複,因為傳入的參數的key就是這個參數名,以此來進行一一對應

快速學習JasperReport-資料填充

(3)模闆參數設定

将設定好的參數直接拖入表格中對應的位置,并設定好大小與對齊方式。

快速學習JasperReport-資料填充

1.1.2 PDF輸出

@GetMapping("/testJasper02")
    public void createPdf(HttpServletRequest request, HttpServletResponse response) 
throws IOException {
        //1.引入jasper檔案
        Resource resource = new ClassPathResource("templates/parametersTest.jasper");
        FileInputStream fis = new FileInputStream(resource.getFile());
        //2.建立JasperPrint,向jasper檔案中填充資料
        ServletOutputStream os = response.getOutputStream();
        try {
            /**
             * parameters集合中傳遞的key需要和設計模闆中使用的name一緻
             */
            HashMap parameters = new HashMap();
            parameters.put("title","使用者詳情");
            parameters.put("username","李四");
            parameters.put("companyName","傳智播客");
            parameters.put("mobile","120");
            parameters.put("departmentName","講師");
            JasperPrint print = JasperFillManager.fillReport(fis, parameters,new JREmptyDataSource());
            //3.将JasperPrint已PDF的形式輸出
            JasperExportManager.exportReportToPdfStream(print,os);
            response.setContentType("application/pdf");
       } catch (JRException e) {
            e.printStackTrace();
       }finally {
            os.flush();
       }
   }      

1.2 資料源填充資料

1.2.1 JDBC資料源

1.2.1.1 配置資料連接配接

使用JDBC資料源填充資料:使用Jaspersoft Studio 先要配置一個資料庫連接配接

​填寫資料源的類型,選擇“Database JDBC Connection”​

快速學習JasperReport-資料填充

​配置資料庫資訊​

快速學習JasperReport-資料填充

這一步,需要:

(1)給建立的這個資料連接配接起個名字;

(2)根據資料庫選擇驅動類型; Jaspersoft Studio 已經

内置了很多常用資料庫的驅動,使用的時候直接選就可以了。當然,如果這還滿足不了你的話,你還可以添加你指定的 JDBC 驅動 jar 包。

1.2.1.2 模闆制作

(1)制作空白模闆

建立空白模闆,并将不需要的Band

(2)将資料庫使用者字段配置到子產品中

為了友善的進行模闆制作,可以将需要資料庫表中的字段添加到Studio中。在outline中右鍵模闆,選擇data set and query

快速學習JasperReport-資料填充

使用者可以在 SQL 查詢語句輸入視窗中,輸入需要查詢資料的查詢語句,點選右上角的“Read Fields”按鈕,界面下方的字段清單中,就會顯示此查詢語句中所涵蓋的所有字段的清單。在後面的報表設計中,我們就可以直接使用這些字段了。

快速學習JasperReport-資料填充

在“Fields”清單中,隻保留報表中使用的字段,其他用不到的字段最好用“Delete”删掉,防止由于資料表變化,導緻報表模闆中的字段設定與資料表對應不上,導緻報表報錯。輸入完畢後,點選“OK”按鈕,系統即會把查詢語句儲存在報表模闆中。

快速學習JasperReport-資料填充

(3)填充Filed

将id,mobile,username等拖入到 Detail Band中設計模闆如下:

快速學習JasperReport-資料填充

1.2.1.3 PDF輸出

//測試JDBC連接配接資料源
    @GetMapping("/testJasper03")
    public void createPdf(HttpServletRequest request, HttpServletResponse response) 
throws Exception {
        //1.引入jasper檔案
        Resource resource = new ClassPathResource("templates/testConn.jasper");
        FileInputStream fis = new FileInputStream(resource.getFile());
        //2.建立JasperPrint,向jasper檔案中填充資料
        ServletOutputStream os = response.getOutputStream();
        try {
            /**
             * 1.jasper檔案流
             * 2.參數清單
             * 3.資料庫連接配接
             */
            HashMap parameters = new HashMap();
            JasperPrint print = JasperFillManager.fillReport(fis, parameters,getConnection());
            //3.将JasperPrint已PDF的形式輸出
            JasperExportManager.exportReportToPdfStream(print,os);
            response.setContentType("application/pdf");
       } catch (JRException e) {
            e.printStackTrace();
       }finally {
            os.flush();
       }
   }
    //建立資料庫Connection
    public Connection getConnection() throws Exception {
        String url = "jdbc:mysql://localhost/ihrm";
        Class.forName("com.mysql.jdbc.Driver");
        Connection conn = DriverManager.getConnection(url, "root", "111111");
        return conn;
   }      

1.2.2 JavaBean資料源

1.2.2.1 建立Filed

(1)建立Filed

快速學習JasperReport-資料填充

(2)構造模闆

快速學習JasperReport-資料填充

1.2.2.2 PDF輸出

(1)配置實體類

public class User {
    private String id;
    private String username;
    private String mobile;
    private String companyName;
    private String departmentName;
    public User(String id, String username, String mobile, String companyName, String
departmentName) {
        this.id = id;
        this.username = username;
        this.mobile = mobile;
        this.companyName = companyName;
        this.departmentName = departmentName;
   }
    public String getId() {
        return id;
   }
    public void setId(String id) {
        this.id = id;
   }
    public String getUsername() {
        return username;
   }
   public void setUsername(String username) {
        this.username = username;
   }
    public String getMobile() {
        return mobile;
   }
    public void setMobile(String mobile) {
        this.mobile = mobile;
   }
    public String getCompanyName() {
        return companyName;
   }
    public void setCompanyName(String companyName) {
        this.companyName = companyName;
   }
    public String getDepartmentName() {
        return departmentName;
   }
    public void setDepartmentName(String departmentName) {
        this.departmentName = departmentName;
   }
}      
//測試javaBean資料源
    @GetMapping("/testJasper04")
    public void createPdf(HttpServletRequest request, HttpServletResponse response) 
throws Exception {
        //1.引入jasper檔案
        Resource resource = new ClassPathResource("templates/testJavaBean.jasper");
        FileInputStream fis = new FileInputStream(resource.getFile());
        //2.建立JasperPrint,向jasper檔案中填充資料
        ServletOutputStream os = response.getOutputStream();
        try {
            HashMap parameters = new HashMap();
            //構造javaBean資料源
            JRBeanCollectionDataSource ds = new
JRBeanCollectionDataSource(getUserList());
            /**
             * 1.jasper檔案流
             * 2.參數清單
             * 3.JRBeanCollectionDataSource
             */
            JasperPrint print = JasperFillManager.fillReport(fis, parameters,ds);
            //3.将JasperPrint已PDF的形式輸出
            JasperExportManager.exportReportToPdfStream(print,os);
            response.setContentType("application/pdf");
       } catch (JRException e) {
            e.printStackTrace();
       }finally {
            os.flush();
       }
   }
    //建立資料庫Connection
    public List<User> getUserList() throws Exception {
        List<User> list = new ArrayList<>();
        for (int i=1;i<=5;i++) {
            User user = new User(i+"", "testName"+i, "10"+i, "企業"+i, "部門"+i);
            list.add(user);
       }
        return list;
   }