如何使用java将参数传递给JasperReport以便稍后在SQL查询中使用

时间:2015-11-27 23:55:46

标签: java parameters jasper-reports

我已经创建了6个Jasper Report模板,所有静态文本字段都要使用SQL查询填写。 SQL查询使用我传入的2个参数: FirstName LastName 。我还传递了另外两个参数,这些参数只会添加到Report。

这是我到目前为止将带有参数的HashMap传递给Report的代码。但我很遗憾,因为我找不到任何好的文档或例子。

package print;
import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.engine.export.*;
import java.util.*;

public class PrintCertificate  
{   
   public PrintCertificate(String output, String certType, String firstName, String lastName, String confirmDate, String pastorName)
   {
    if(certType=="rci_eng")
    {
        String fileName = "/RCI_Eng.jasper";
        output = "C:/Users/User/Desktop/Test/";

        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("FirstName",firstName);
        map.put("LastName",lastName);
        map.put("PastorName", pastorName);
        map.put("DateOfConfirmation", confirmDate);
        try
        {
            JasperPrint print = JasperFillManager.fillReport(fileName, map);
            JRDocxExporter exporter = new JRDocxExporter();
            exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
            exporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, "test.docx");
            exporter.exportReport(print);

        }
        catch (Exception e)
        {
            e.printStackTrace();
            System.exit(1);
        }
    }
  }
}

我知道这可能远非正确,但如果有人能指出我正确的文档或示例方向,或指出我做错了什么,那将会有很大的帮助!

1 个答案:

答案 0 :(得分:4)

  

以下是将Jasper报告与Java应用程序一起使用的简要说明

  • 首先,您必须设置与报告的数据库连接。

enter image description here

  • 然后您可以为报告设计SQL查询。

    enter image description here 如果需要通过查询过滤数据,可以向SQL查询添加参数。只需使用新参数按钮添加参数,就可以将显示在文本区域内的参数拖放到查询中。 / LI>

在报告检查器中,您可以在字段类别下查看查询的所有列名称,并在参数类别下定义所有参数。

enter image description here

  • 您可以设计如下的基本报告

    通过将字段名称和参数拖放到报表设计器,您可以根据需要设计报表。 标题带(此处为您的标题),列标题带(列名称),详细信息带(此处为迭代数据)和摘要带(如同Grand_Total,日期,发布者和图表元素可添加到此部分)足以用于基本报告。

    enter image description here
  • 然后您可以声明 ReportGenarator 类来生成您的 报告

    Map<String, Object> map = new HashMap<>();
                map.put("headding", "REPORT FROM DATABASE CONNECTION");//parameter name should be like it was named inside your report.
                new ReportGenarator().genarateReport(
                        ReportGenarator.REPORT, map, your_DB_connction_reference_here);
    
  • 您可以通过按应用程序中的按钮生成报告。因此,您必须在按钮内包含以下代码 行动事件

    import urllib
    import chardet
    
    
    def main():
        page = urllib.urlopen('http://bbc.com')
        content = page.read()
    
        # detect the encoding
        try:
            encoding = chardet.detect(content)['encoding']
        except:
            # use utf-8 as default encoding
            encoding = 'utf-8'
    
        # decode the content into unicode
        content = content.decode(encoding)
    
        # write to file
        with open('test.txt', 'wb') as f:
            f.write(content.encode('utf-8'))