7.5. 使用 Groovy 模板引擎的 HTML 报表

该示例是基于 Library 应用程序,其源码可以在 GitHub 找到。我们创建一个报表展示选中城市的图书出版物。输出格式是 HTML。

  1. 使用 JPQL 数据集创建报表:

    html groovy template structure
    Figure 67. 报表数据结构

    BookPublications 区域用来输出图书出版物列表,使用如下 JPQL 查询语句:

    BookPublications 数据集
    select
    book.name as "book",
    publisher.name as "publisher"
    from library$BookPublication e
    left join e.book book
    left join e.publisher publisher
     where e.town.id = ${city}

    这个查询使用了外部的报表参数 - city。该参数是 Entity 类型;但是,在 JPQL 查询语句中可以直接用来跟实体标识符进行比较;后台会自动做转换。

  2. 报表参数描述:

    Parameters and Formats 标签页声明了一个报表外部参数 – City

    html groovy template parameter
    Figure 68. 报表参数

    当运行报表时,用户必须输入该参数。城市的选择会通过 library$Town.browse 界面进行,这个界面在应用程序内是可用的。

  3. 创建一个报表模板

    Templates 标签页定义了一个 HTML 模板,使用 FreeMarker 标签默认生成。

    使用下面内容创建新的 HTML 文件:

    PublicationsTemplate
    <?xml version="1.0" encoding="utf-8"?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ru">
       <head>
          <title> Publications by city </title>
          <style type="text/css">
     body {font: 12pt Georgia, "Times New Roman", Times, serif; line-height: 1.3; padding-top: 30px;} tbody tr {height:40px; min-height:20px}
          </style>
       </head>
       <body>
          <h1>Publications, published in <% out << "${Root.fields.city.name}"%></h1>
              <% def bookPublications = Root.bands.BookPublications.fields %>
          <table class="report-table" border="1" cellspacing="2" >
             <thead>
             <tr>
                <th>Book</th>
                <th>Publisher</th>
             </tr>
             </thead>
             <tbody>
                <% bookPublications.title.eachWithIndex{elem, index -> out << "<tr><td> ${bookPublications.book[index]} </td><td> ${bookPublications.publisher[index]} </td></tr>"}%>
             </tbody>
          </table>
       </body>
    </html>

    输入参数的值用来生成报表标题:${Root.fields.city.name}

    bookPublications 变量定义如下:

    <% def bookPublications = Root.bands.BookPublications.fields %>

    该变量在表格体中用来显示报表字段。

    <% bookPublications.title.eachWithIndex{elem, index -> out << "<tr><td> ${bookPublications.book[index]} </td><td> ${bookPublications.publisher[index]} </td></tr>"}%>

    上传新的模板,然后选择 HTML 输出类型,在 Template type 单选按钮组选择 Groovy template 并设置为默认:

    publicationsTemplate editor
    Figure 69. 报表模板编辑器

运行模板,确保其工作正常:

publications report
Figure 70. 报表结果