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

Understanding the basics of Jasper reporting with Java

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

            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();

它使用上面的代码生成报告。但是,有些地方我在理解的过程中发现了一些问题。

谢谢!

Where is the Query String?

在报告模板 (jrxml) 中

Do I have to create the jrxml file separately, which contains the query string and name that file as myreport.jrxml?

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

这套教程是 good.I 使用这些视频从头开始学习的 ireports。 [https://www.youtube.com/watch?v=nM7Xsr-_8_g][1]

您可以使用 iReport 设计器创建 .jrxml files.Then 添加 .jrxml 文件和 .jasper 文件(在编译报告后生成)到 project.Here 如何生成报告的示例在 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();

        }
    }

在 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 class

加载单个(主)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 class

加载子报告(编号)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);
}

编写动作class调用jasper模块

import com.opensymphony.xwork2.ActionSupport;

public class 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;
}

}