JasperRepor导出报表通用类

1.ReportUtils.java通用类

/**
 * 使用jasperReport做报表时的工具支持类.有两个用途,生成jasperPrint对象,和设置导出时的session
 */
public class ReportUtils {
	private HttpServletRequest request;
	private HttpServletResponse response;
	private HttpSession session;

	public ReportUtils(HttpServletRequest request, HttpServletResponse response) {
		this.request = request;
		this.session = request.getSession();
		this.response = response;
	}

	/**
	 * 获得JasperPrint对象;自定义填充报表时的parameter和dataSource. 参数说明和动态表头的用法参考上一方法
	 */
	public JasperPrint getJasperPrint(String filePath, Map parameter,
			JRDataSource dataSource) throws JRException {
		JasperReport jasperReport = null;
		try {
			jasperReport = (JasperReport) JRLoader.loadObject(filePath);
			return JasperFillManager.fillReport(jasperReport, parameter,
					dataSource);
		} catch (JRException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 获得JasperPrint对象;自定义填充报表时的parameter和connection
	 */
	public JasperPrint getJasperPrint(String filePath, Map parameter,
			Connection  conn) throws JRException {
		JasperReport jasperReport = null;
		try {
			jasperReport = (JasperReport) JRLoader.loadObject(filePath);
			return JasperFillManager.fillReport(jasperReport, parameter,
					conn);
		} catch (JRException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 通过传入List类型数据源获取JasperPrint实例
	 */
	public JasperPrint getPrintWithBeanList(String filePath, Map parameter,
			List list) throws JRException {
		JRDataSource dataSource = new JRBeanCollectionDataSource(list);
		return getJasperPrint(filePath, parameter, dataSource);
	}

	/**
	 * 传入类型,获取输出器
	 * 
	 * @param docType
	 * @return
	 */
	public JRAbstractExporter getJRExporter(DocType docType) {
		JRAbstractExporter exporter = null;
		switch (docType) {
		case PDF:
			exporter = new JRPdfExporter();
			break;
		case HTML:
			exporter = new JRHtmlExporter();
			break;
		case XLS:
			exporter = new JExcelApiExporter();
			break;
		case XML:
			exporter = new JRXmlExporter();
			break;
		case RTF:
			exporter = new JRRtfExporter();
			break;
		case CSV:
			exporter = new JRCsvExporter();
			break;
		case TXT:
			exporter = new JRTextExporter();
			break;
		}
		return exporter;
	}

	/**
	 * 获得相应类型的Content type
	 * @param docType
	 * @return
	 */
	public String getContentType(DocType docType){
		String contentType="text/html";
		switch(docType){
		case PDF:
			contentType = "application/pdf";
			break;
		case XLS:
			contentType = "application/vnd.ms-excel";
			break;
		case XML:
			contentType = "text/xml";
			break;
		case RTF:
			contentType = "application/rtf";
			break;
		case CSV:
			contentType = "text/plain";
			break;
		}
		return contentType;
	}

	public void setAttrToPage(JasperPrint jasperPrint, String report_fileName,
			String report_type) {
		session.setAttribute("REPORT_JASPERPRINT", jasperPrint);
		session.setAttribute("REPORT_FILENAME", report_fileName);
		session.setAttribute("REPORT_TYPE", report_type);
	}

	/**
	 * 定义了报表输出类型,固定了可输出类型
	 */
	public static enum DocType {
		PDF, HTML, XLS, XML, RTF, CSV, TXT
	}

	/**
	 * 编译报表模板文件jrxml,生成jasper二进制文件
	 * 
	 * @param jrxmlPath
	 * @param jrsperPath
	 * @throws JRException
	 */
	public void complieJrxml(String jrxmlPath, String jasperPath)
			throws JRException {
		JasperCompileManager.compileReportToFile(jrxmlPath, jasperPath);
	}

	/**
	 * 输出html静态页面,必须注入request和response
	 * 
	 * @param jasperPath
	 * @param params
	 * @param sourceList
	 * @param imageUrl
	 *            报表文件使用的图片路径,比如 ../servlets/image?image=
	 * @throws JRException
	 * @throws IOException
	 * @throws ServletException
	 */
	public void servletExportHTML(String jasperPath, Map params,
			List sourceList, String imageUrl) throws JRException, IOException,
			ServletException {
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		JRAbstractExporter exporter = getJRExporter(DocType.HTML);

		JasperPrint jasperPrint = getPrintWithBeanList(jasperPath, params,
				sourceList);

		session.setAttribute(
				ImageServlet.DEFAULT_JASPER_PRINT_SESSION_ATTRIBUTE,
				jasperPrint);

		PrintWriter out = response.getWriter();

		exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
		exporter.setParameter(JRExporterParameter.OUTPUT_WRITER, out);
		exporter.setParameter(JRHtmlExporterParameter.IMAGES_URI, imageUrl);
		exporter.setParameter(JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN,false);//不显示px
		exporter.setParameter(JRHtmlExporterParameter.IS_OUTPUT_IMAGES_TO_DIR, Boolean.FALSE);
		exporter.setParameter(JRHtmlExporterParameter.BETWEEN_PAGES_HTML, "<br style='page-break-before:always;'>"); 

		exporter.exportReport();
	}

	/**
	 * 输出html静态页面,必须注入request和response
	 * 
	 * @param jasperPath
	 * @param params
	 * @param sourceList
	 * @param imageUrl
	 *            报表文件使用的图片路径,比如 ../servlets/image?image=
	 * @throws JRException
	 * @throws IOException
	 * @throws ServletException
	 */
	public void servletExportHTML(String jasperPath, Map params,
			Connection conn, String imageUrl) throws JRException, IOException,
			ServletException {
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		JRAbstractExporter exporter = getJRExporter(DocType.HTML);

		JasperPrint jasperPrint = getJasperPrint(jasperPath, params,
				conn);

		session.setAttribute(
				ImageServlet.DEFAULT_JASPER_PRINT_SESSION_ATTRIBUTE,
				jasperPrint);

		PrintWriter out = response.getWriter();

		exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
		exporter.setParameter(JRExporterParameter.OUTPUT_WRITER, out);
		exporter.setParameter(JRHtmlExporterParameter.IMAGES_URI, imageUrl);
		exporter.setParameter(JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN,false);//不显示px
		exporter.setParameter(JRHtmlExporterParameter.IS_OUTPUT_IMAGES_TO_DIR, Boolean.FALSE);

		exporter.exportReport();
	}

	/**
	 * 生成不同格式报表文档
	 * 
	 * @param docType
	 *            文档类型
	 * @param jasperPath
	 */
	public void servletExportDocument(DocType docType, String jasperPath,
			Map params, List sourceList, String fileName) throws JRException,
			IOException, ServletException {

		if (docType == DocType.HTML) {
			servletExportHTML(jasperPath, params, sourceList, fileName);
			return;
		}

		JRAbstractExporter exporter = getJRExporter(docType);
		// 获取后缀
		String ext = docType.toString().toLowerCase();

		if (!fileName.toLowerCase().endsWith(ext)) {
			fileName += "." + ext;
		}
		// 判断资源类型
		if (ext.equals("xls")) {
			// 要想获得更好的视觉效果,可以添加以下代码
			 exporter.setParameter(
			 JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS,
			 Boolean.TRUE); // 删除记录最下面的空行
			
			 exporter.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET,
			 Boolean.FALSE);// 删除多余的ColumnHeader
			
			 exporter.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND
			 , Boolean.FALSE);// 显示边框
		}

		response.setContentType(getContentType(docType));
		response.setHeader("Content-Disposition", "attachment; filename=\""
				+ URLEncoder.encode(fileName, "UTF-8") + "\"");

		exporter.setParameter(JRExporterParameter.JASPER_PRINT,
				getPrintWithBeanList(jasperPath, params, sourceList));
		
		OutputStream outStream = null;
		PrintWriter outWriter = null;
		
		if(ext.equals("csv")){//解决中文乱码问题
			response.setCharacterEncoding("GBK");
			outWriter = response.getWriter();
			exporter.setParameter(JRExporterParameter.OUTPUT_WRITER,outWriter);
		}else{
			outStream = response.getOutputStream();
			exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, outStream);
			if(ext.equals("txt")){
				exporter.setParameter(JRTextExporterParameter.CHARACTER_WIDTH, new Integer(80));
			    exporter.setParameter(JRTextExporterParameter.CHARACTER_HEIGHT, new Integer(25));
			    exporter.setParameter(JRTextExporterParameter.CHARACTER_ENCODING,"GBK");
			}
		}
		try {
			exporter.exportReport();
		} catch (JRException e) {
			throw new ServletException(e);
		} finally {
			if (outStream != null) {
				try {
					outStream.close();
				} catch (IOException ex) {
				}
			}
		}
	}

	/**
	 * 生成不同格式报表文档
	 * 
	 * @param docType
	 *            文档类型
	 * @param jasperPath
	 */
	public void servletExportDocument(DocType docType, String jasperPath,
			Map params, Connection conn, String fileName) throws JRException,
			IOException, ServletException {

		if (docType == DocType.HTML) {
			servletExportHTML(jasperPath, params, conn, fileName);
			return;
		}

		JRAbstractExporter exporter = getJRExporter(docType);
		// 获取后缀
		String ext = docType.toString().toLowerCase();

		if (!fileName.toLowerCase().endsWith(ext)) {
			fileName += "." + ext;
		}
		// 判断资源类型
		if (ext.equals("xls")) {
			// 要想获得更好的视觉效果,可以添加以下代码
			 exporter.setParameter(
			 JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS,
			 Boolean.TRUE); // 删除记录最下面的空行
			
			 exporter.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET,
			 Boolean.FALSE);// 删除多余的ColumnHeader
			
			 exporter.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND
			 , Boolean.FALSE);// 显示边框
		}

		response.setContentType(getContentType(docType));
		response.setHeader("Content-Disposition", "attachment; filename=\""
				+ URLEncoder.encode(fileName, "UTF-8") + "\"");

		exporter.setParameter(JRExporterParameter.JASPER_PRINT,
				getJasperPrint(jasperPath, params, conn));
		
		OutputStream outStream = null;
		PrintWriter outWriter = null;
		
		if(ext.equals("csv")){//解决中文乱码问题
			response.setCharacterEncoding("GBK");
			outWriter = response.getWriter();
			exporter.setParameter(JRExporterParameter.OUTPUT_WRITER,outWriter);
		}else{
			outStream = response.getOutputStream();
			exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, outStream);
			if(ext.equals("txt")){
				exporter.setParameter(JRTextExporterParameter.CHARACTER_WIDTH, new Integer(80));
			    exporter.setParameter(JRTextExporterParameter.CHARACTER_HEIGHT, new Integer(25));
			    exporter.setParameter(JRTextExporterParameter.CHARACTER_ENCODING,"GBK");
			}
		}
		try {
			exporter.exportReport();
		} catch (JRException e) {
			throw new ServletException(e);
		} finally {
			if (outStream != null) {
				try {
					outStream.close();
				} catch (IOException ex) {
				}
			}
		}
	}

}


2.用Servlet导出生成文件

public class JapserReportServlet extends HttpServlet{

	private static final long serialVersionUID = 1L;
	public void init(){}
	
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException{
		String docType = request.getParameter("docType");
		String jasperFile = request.getParameter("jasperFile");
		String isBean = request.getParameter("isBean");//数据提供方式
		
		String fileName = new String(request.getParameter("fileName").getBytes("ISO-8859-1"),"UTF-8");
		//jasper文件放在应用根目录的reports中
		String jasperPath = request.getSession().getServletContext().getRealPath("/") + "/reports/"+ jasperFile;
		
		if(StringUtils.isNotEmpty(jasperPath)){

			if(StringUtils.isEmpty(fileName)){
				fileName = "报表";
			}
			
			ReportUtils jasperReport = new ReportUtils(request,response);

			//传递报表中(SQL)用到的参数值:$P{ProjectName}
			Map params = new HashMap();
		    //"Name"是报表中定义过的一个参数名称,其类型为String 型 
		    //params.put("ProjectName", new String("Project1"));

			try {
				if(isBean.equals("1")){
					jasperReport.servletExportDocument(getEnumDocType(docType), jasperPath, params, getSourceList(), fileName);
				}else{
					jasperReport.servletExportDocument(getEnumDocType(docType), jasperPath, params, getConnection(), fileName);
				}
			
			} catch (JRException e) {
				e.printStackTrace();
			} catch (ServletException e) {
				e.printStackTrace();
			}
		}else{
			response.setCharacterEncoding("UTF-8");
			response.sendError(-1, "出错:jasperPath参数是必须的!");
		}
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException{       
		this.doGet(request, response);              
	} 
	
    public void destroy() {       
        super.destroy();        
    }
    
    public static DocType getEnumDocType(String docType){
    	DocType type = DocType.HTML;
    	docType = docType.toUpperCase();
    	if(docType.equals("PDF")){
    		type = DocType.PDF;
    	}else if(docType.equals("XLS")){
    		type = DocType.XLS;
    	}else if(docType.equals("XML")){
    		type = DocType.XML;
    	}else if(docType.equals("RTF")){
    		type = DocType.RTF;
    	}else if(docType.equals("CSV")){
    		type = DocType.CSV;
    	}else if(docType.equals("TXT")){
    		type = DocType.TXT;
    	}
    	return type;
    }
    
    /***数据对象****/
    public static List getSourceList(){
    	List<TUser> sourceList = new ArrayList<TUser>();// 测试数据源
		for (int i = 0; i < 15; i++) {
			TUser user = new TUser();
			user.setId(1000 + i);
			user.setUsername("user_" + i);
			user.setPassword("*******");
			sourceList.add(user);
		}
    	return sourceList;
    }
    
    /****数据库连接****/
	public static Connection getConnection() {
		Connection conn = null;
		String driver = "com.mysql.jdbc.Driver";
		String url = "jdbc:mysql://127.0.0.1/springapp?useUnicode=true&characterEncoding=gb2312";
		try {
			Class.forName(driver);
			conn = DriverManager.getConnection(url,"root", "root");
			return conn;
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException ex) {
			ex.printStackTrace();
		}
		return null;
	}
}

3.web.xml中的Servlet配置

 

	<servlet>
        <servlet-name>JapserReportServlet</servlet-name>
        <servlet-class>
            com.logcd.servlet.JapserReportServlet
        </servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>JapserReportServlet</servlet-name>
        <url-pattern>/reports</url-pattern>
    </servlet-mapping>


4.调用

function jasperReport(docType){
	var jasperFile = "Regist_User_Group.jasper";
	var paramStr = "?docType=" + docType + "&jasperFile="+jasperFile + "&fileName=" +'人员名单列表' + "&isBean=0";
	var url = getCurrentDirectory() + "/reports" + paramStr;
	window.open(url);
}

/***获取当前路径***/
function getCurrentDirectory(){
	var locHref = location.href;
	var locArray = locHref.split("/");
    delete locArray[locArray.length-1];
    var dirStr = locArray.join("/");
    return dirStr;
}


 

		报表类型
		<select name="reportType" id="reportType">
			 <option value="html">HTML</option>
			 <option value="pdf">PDF</option>
			 <option value="rtf">RTF</option>
			 <option value="xls">XLS</option>
			 <option value="xml">XML</option>
			 <option value="csv">CSV</option>
			 <option value="txt">TXT</option>
	    </select> 
		<button onclick="jasperReport($('reportType').value);">Reports</button>


5.直接生产文件

public class FirstJasperReports {
	 static String fileName="E:/workspace/js_test/jrxml/HelloWorld.jrxml";
	    public static void main(String[] args)throws Exception{
	        long startTime=System.currentTimeMillis();
	        //将报表的定义文件HelloWorld.jrxml编译成HelloWorld.jasper文件
	        String jasperFile=JasperCompileManager.compileReportToFile(fileName);
	        //向HelloWorld.jasper文件中填充数据,这一步将生产出HelloWorld .jrprint文件
	        String jrprintFile=JasperFillManager.fillReportToFile(jasperFile,null,new JREmptyDataSource());
	        //将.jrprint文件转换成HTML格式
	        JasperExportManager.exportReportToHtmlFile(jrprintFile);
	        //将.jrprint文件转换成PDF格式
	        
	        //JasperExportManager.exportReportToPdfFile(jrprintFile);
	        //将.jrprint文件转换成XML格式
	        JasperExportManager.exportReportToXmlFile(jrprintFile,false);
	        //将.jrprint文件转换成XLS格式(即Excel文件),需要用到POI类库.
	        File sourceFile = new File(jrprintFile);
	        JasperPrint jasperPrint = (JasperPrint)JRLoader.loadObject(sourceFile);
	        File destFile = new File(sourceFile.getParent(), jasperPrint.getName() + ".xls");
	        JRXlsExporter exporter = new JRXlsExporter();
	        exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
	        exporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, destFile.toString());
	        exporter.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET, Boolean.TRUE);
	        exporter.exportReport();
	        long endTime=System.currentTimeMillis();
	        long time=(endTime-startTime)/1000;
	        System.out.println("success with "+time+" s");
	     }

}


 

posted on 2012-04-09 11:05  熊哥club  阅读(456)  评论(0编辑  收藏  举报

熊哥club Fork me on GitHub