了解使用Java进行Jasper报告的基础知识

时间:2015-02-08 07:31:07

标签: java jasper-reports

我刚开始用Jasper reports学习Java。我在网上搜索过,并没有找到一个从一开始就教授报告的好教程。 Tutorialspoint.com有一个很好的,但他们使用ANT。之后我可以学习它们,但我现在需要的是使用简单的Java程序生成jasper reports。 我找到了来自github的{​​{3}}代码,但我在理解代码时遇到了一些问题。

            String reportName = "myreport";
            Map<String, Object> parameters = new HashMap<String, Object>();
            connection = new ConnectionFactory().getConnection(); // opens a jdbc connection

            // compiles jrxml
            JasperCompileManager.compileReportToFile(reportName + ".jrxml");
            // fills compiled report with parameters and a connection
            JasperPrint print = JasperFillManager.fillReport(reportName + ".jasper", parameters, connection);
            // exports report to pdf
            JRExporter exporter = new JRPdfExporter();
            exporter.setParameter(JRExporterParameter.JASPER_PRINT, print);
            exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, new FileOutputStream(reportName + ".pdf")); // your output goes here

            exporter.exportReport();

使用上面的代码生成报告。但是,在理解时我会发现一些问题。

  • 查询字符串在哪里?
  • 我是否必须单独创建jrxml文件,其中包含查询字符串并将该文件命名为myreport.jrxml

谢谢!

3 个答案:

答案 0 :(得分:1)

  

查询字符串在哪里?

在报告模板(jrxml)

  

我是否必须单独创建jrxml文件,其中包含查询字符串并将该文件命名为myreport.jrxml?

是。您可以使用iReport或JasperReport Studio来创建jrxml。

答案 1 :(得分:1)

这套教程很好。我从一开始就使用这些视频学习了ireports。 [https://www.youtube.com/watch?v=nM7Xsr-_8_g][1]

您可以使用iReport设计器创建.jrxml文件。然后将.jrxml文件和.jasper文件(在编译报告后生成)添加到项目中。以下是如何在java程序中生成报告的示例

public void Report(String from,String to){
        Connection conn=null;
         try {

            conn = Database.con();

            JasperDesign jd = JRXmlLoader.load("src\\Reports\\report5.jrxml");
            String sql = "SELECT login.`Username` AS login_Username, login.`date` AS login_date, "
                    + "login.`task` AS login_task FROM `login` login where date(login.`date`) between '"+from+"'  and '"+to+"'";
            JRDesignQuery newQuery = new JRDesignQuery();
            newQuery.setText(sql);
            jd.setQuery(newQuery);
            JasperReport jr = JasperCompileManager.compileReport(jd);
            JasperPrint jp = JasperFillManager.fillReport(jr, null, conn);
            JasperViewer.viewReport(jp, false);


        } catch (ClassNotFoundException | SQLException | JRException e) {
            JOptionPane.showMessageDialog(null, e);
            e.printStackTrace();

        }
    }

答案 2 :(得分:0)

尝试首先创建以下getter setter

private JasperPrint jasperPrint = null;
private JasperReport jasperReport = null;
private Map<String, Object> parameters = null;
private String applicationPath = null;

下一个创建构造函数

public JasperReportModel(String applicationPath) {
    super();
    this.applicationPath = applicationPath;
}

现在编写生成pdf文件的逻辑

public String generatePDFReport(Collection collection, String storageDir, String fileName) throws Exception {
    JRBeanCollectionDataSource beanColDataSource = null;
    String filePath = "";
    try {
        beanColDataSource = new JRBeanCollectionDataSource(collection);
        jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, beanColDataSource);
        filePath = storageDir+File.separator+fileName+".pdf";
        JasperExportManager.exportReportToPdfFile(jasperPrint, filePath);
    } catch(Exception e) {
        //e.printStackTrace();
        throw e;
    }
    return filePath;
}

现在编写excel文件的逻辑

public String generateXLSXReport(Collection collection, String storageDir, String fileName) throws Exception {
    JRBeanCollectionDataSource beanColDataSource = null;
    String filePath = "";
    JRXlsxExporter exporter = null;
    SimpleXlsxReportConfiguration configuration = null;
    try {
        beanColDataSource = new JRBeanCollectionDataSource(collection);
        jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, beanColDataSource);
        filePath = storageDir+File.separator+fileName+".pdf";
        //Create Exporter (Input / Output)
        exporter = new JRXlsxExporter();
        exporter.setExporterInput(new SimpleExporterInput(jasperPrint));
        exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(new File(filePath)));
        //Set configuration as you like it!!
        configuration = new SimpleXlsxReportConfiguration();
        configuration.setOnePagePerSheet(false);
        configuration.setDetectCellType(true);
        configuration.setWhitePageBackground(true);
        configuration.setIgnorePageMargins(true);
        configuration.setMaxRowsPerSheet(65000);
        configuration.setForcePageBreaks(false);
        configuration.setWrapText(true);
        exporter.setConfiguration(configuration);
        exporter.exportReport();
    }catch(Exception e){
        //e.printStackTrace();
        throw e;
    }
    return filePath;
}

从java类加载单个(主)jrxml文件的逻辑

public void loadJasperReport(String templateName) throws JRException {
    File jrxmlFile = new File(applicationPath+File.separator+templateName+".jrxml");
    File jasperFile = new File(applicationPath+File.separator+"jasper"+File.separator+templateName+".jasper");
    if(jrxmlFile.exists() && !jasperFile.exists() ) {
        JasperCompileManager.compileReportToFile(jrxmlFile.getAbsolutePath(), jasperFile.getAbsolutePath());
    }
    jasperReport = (JasperReport) JRLoader.loadObjectFromFile(jasperFile.getPath());        
    parameters = new HashMap<String, Object>();
    parameters.put("applicationPath", applicationPath);
}

从java类加载子报告(no:of)jrxml文件的逻辑

public void loadJasperReport(String templateName, int noOfSubReport) throws JRException {
    File jrxmlSubReport = null, jasperSubReport = null;
    for(int i = 1; i <= noOfSubReport; i++) {
        jrxmlSubReport = new File(applicationPath+File.separator+templateName+"_"+i+".jrxml");
        jasperSubReport = new File(applicationPath+File.separator+"jasper"+File.separator+templateName+"_"+i+".jasper");
        if( jrxmlSubReport.exists() && !jasperSubReport.exists() ) {
            JasperCompileManager.compileReportToFile(jrxmlSubReport.getAbsolutePath(), jasperSubReport.getAbsolutePath());
        }
    }

    File jrxmlFile = new File(applicationPath+File.separator+templateName+".jrxml");
    File jasperFile = new File(applicationPath+File.separator+"jasper"+File.separator+templateName+".jasper");
    if( jrxmlFile.exists() && !jasperFile.exists() ) {
        JasperCompileManager.compileReportToFile(jrxmlFile.getAbsolutePath(), jasperFile.getAbsolutePath());
    }
    jasperReport = (JasperReport) JRLoader.loadObjectFromFile(jasperFile.getPath());        
    parameters = new HashMap<String, Object>();
    parameters.put("applicationPath", applicationPath+File.separator);
}

编写动作类来调用jasper模块

import com.opensymphony.xwork2.ActionSupport;

公共类ActionClass扩展了ActionSupport {

public String downloadReport(){
    String jasperFilePath="";
    JasperReportModel jasperModel = null;
    ActionSupport actionSupport = null;
    String dwnFilePath="", dwnFileName="", filePath="";
    try{
        if(isError){
            return "internalError";
        }
        DAOImpl impl= new DAOImpl();
        data = impl.getadmlistforReport("your bean class object");
        jasperFilePath = getText("pdf file path from properties file");
        jasperModel = new JasperReportModel(jasperFilePath);
        jasperModel.loadJasperReport("jrxml file name/path");
        dwnFilePath = getText("download file path from");
        String dateTimeString= new SimpleDateFormat("dd_MM_yy_hhmmss_SSS").format(new Date());
        dwnFileName = "c" + dateTimeString;
        if(report_type.equalsIgnoreCase("PDF")){
            filePath = jasperModel.generatePDFReport(data, dwnFilePath, dwnFileName);
            fileName = "report.pdf";
        }
        else if(report_type.equalsIgnoreCase("XLS")){
            filePath = jasperModel.generateXLSReport(data, dwnFilePath, dwnFileName);
            fileName = "report.xls";
        }
        else if(report_type.equalsIgnoreCase("XLSX")){
            filePath = jasperModel.generateXLSXReport(data, dwnFilePath, dwnFileName);
            fileName = "report.xlsx";
        }
        setFileInputStream(new BufferedInputStream(new FileInputStream(filePath)));
        //setFileName(new File(filePath).getName());
        System.out.println("The Download File : " + filePath);
    } catch(Exception e) {
        e.printStackTrace();            
    }       
    return SUCCESS;
}

}