如何将Date作为参数传递给jasper报告

我正在尝试创建JR报告,它将start_date和end_date作为参数。

查询:

SELECT * FROM emp WHERE joining_date BETWEEN $P{frm_date} AND $P{to_date} 

代码:

 Date from_date = dt_from_date.getDate(); Date to_date = dt_to_date.getDate(); java.sql.Date frm_dte = new java.sql.Date(from_date.getTime()); java.sql.Date to_dte = new java.sql.Date(to_date.getTime()); try { HashMap map = new HashMap(); map.put("$P{frm_date}", frm_dte); map.put("$P{to_date}", to_dte); JasperPrint jp = JasperFillManager.fillReport(is, map, con); JRViewer jv = new JRViewer(jp); JFrame jf = new JFrame(); jf.getContentPane().add(jv); jf.validate(); jf.setVisible(true); jf.setSize(new Dimension(800, 600)); jf.setLocation(300, 100); jf.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE); } catch (JRException ex) { ex.printStackTrace(); } 

我们可以将两个参数传递给表中的同一列吗? 例如:

 map.put("joining_date", frm_dte); map.put("joining_date", to_dte); 

你的代码错了。

你应该传递如下参数:

 Map map = new HashMap(); map.put("frm_date", frm_dte); map.put("to_date", to_dte); 

您无需在参数名称中添加P${}


JasperReports分发包中有很多样本。

您可以查看此示例以获取更多详细信息。

您可以将日期作为字符串格式类型传递如下,

 if(from_date!=null) { formattedEndDate=new SimpleDateFormat("yyyy-MM-dd").format(from_date); } if(getStartDate()!=null) { formattedStartDate=new SimpleDateFormat("yyyy-MM-dd").format(to_date); } 
 private JasperPrint generateReport() { Connection conn = null; JasperPrint myJPrint = null; try { conn =yourconnectionName; // parameters to be passed to the report Map params = new HashMap(); // Loading my jasper file JasperDesign jasperDesign = null; JasperReport jasperReport = null; params.put("REPORT_DIR",yourClassName.class.getClassLoader() .getResource("yourJasperFileName.jrxml").toString().replace("yourJasperFileName.jrxml", "")); jasperDesign = JasperManager.loadXmlDesign(yourClassName.class .getClassLoader().getResourceAsStream("yourJasperFileName.jrxml")); params.put("joining_date", frm_dte); params.put("leaving_date", frm_dte); jasperReport = JasperCompileManager.compileReport(jasperDesign); /* * Filling the report with data from the database based on the * parameters passed. */ myJPrint = JasperFillManager.fillReport(jasperReport, params, conn); params.clear(); } catch (JRException ex) { ex.printStackTrace(); } return myJPrint; }