iReport ,jasperReport 事例代码

package com.neusoft.ncm.sys.utility;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.HashMap;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporter;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.util.JRLoader;

public class JasperTest2 {

	/**
	 * Discription:[方法功能中文描述]
	 * 
	 * @param args
	 */
	public static void main(String[] args) {
		String fileName = "E:/testReport.jasper";
		String outFileName = "E:/testReport.html";

		
		HashMap hm = new HashMap();
		Connection connection = null;
		try {
			Class.forName("oracle.jdbc.driver.OracleDriver");
			String url = "jdbc:oracle:thin:@localhost:1521:orcl";
			connection = DriverManager.getConnection(url, "username",
					"password");
			hm.put("ReportTitle", "测试报表");
			hm.put("init", "16923513");
			
			JasperPrint print = JasperFillManager.fillReport(fileName,hm,connection);

			JRExporter exporter = new net.sf.jasperreports.engine.export.JRHtmlExporter();
			
			exporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME,outFileName);
			exporter.setParameter(JRExporterParameter.JASPER_PRINT, print);
			exporter.exportReport();

			System.out.println("Created file: " + outFileName);
		} catch (JRException e) {
			e.printStackTrace();
			System.exit(1);
		} catch (Exception e) {
			e.printStackTrace();
			System.exit(1);
		} finally {
			if (connection != null) {
				try {
					connection.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
	}
}  



简单说明下:
 在工程中创建一个类似的main方法,然后准备个 编译好的 模版文件,就可以了。
需要注意的几点:
jar包的版本:工程中引用的jar包版本一定要和iReport使用的jar包版本一致,我的工程用的iReport版本是 5.0.4,之前由于版本不一致,每次运行到 JasperFillManager.fillReport 这个方法时,就报 java.lang.NullPointerException 这个错误,花了两天才搞定。
工程中需要的jar包,可以去 iReport  的安装目中中找到,然后拷到你的java工程中,这样就一致了。
另外 这个 hm 是报表需要的参数,如果你的报表中需要参数,那么要像这样 hm.put("init", "16923513"); 给set 进去,如果报表 不需要参数,这个值可以为空,不影响工程的运行。
 

你可能感兴趣的:(java,IREPORT,jasperReport)