JasperRepor导出报表通用类-阿里云开发者社区

开发者社区> 熊哥club> 正文

JasperRepor导出报表通用类

简介: 1.ReportUtils.java通用类 /** * 使用jasperReport做报表时的工具支持类.有两个用途,生成jasperPrint对象,和设置导出时的session */ public class ReportUtils { private HttpServletRequest request; private HttpServletResponse r
+关注继续查看

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");
	     }

}


 

版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。

相关文章
阿里云服务器怎么设置密码?怎么停机?怎么重启服务器?
如果在创建实例时没有设置密码,或者密码丢失,您可以在控制台上重新设置实例的登录密码。本文仅描述如何在 ECS 管理控制台上修改实例登录密码。
8502 0
【springboot+easypoi】大数据量excel导出
上次写了一行代码解决导出导入,没看的小伙伴建议先看下《【springboot+easypoi】一行代码搞定excel导入导出》,但是实际业务中遇到一个问题,如果数据里比较大的时候,例如10w+数据一次导出,就会出现卡死情况,继续看官方文档,有大数据量...
2849 0
asp.net 水晶报表使用总结
手头上的一个项目,终显雏形,其中遇到一些问题,经过多番努力,终于得以解决,主要是水晶报表方面的。
775 0
阿里云服务器端口号设置
阿里云服务器初级使用者可能面临的问题之一. 使用tomcat或者其他服务器软件设置端口号后,比如 一些不是默认的, mysql的 3306, mssql的1433,有时候打不开网页, 原因是没有在ecs安全组去设置这个端口号. 解决: 点击ecs下网络和安全下的安全组 在弹出的安全组中,如果没有就新建安全组,然后点击配置规则 最后如上图点击添加...或快速创建.   have fun!  将编程看作是一门艺术,而不单单是个技术。
10326 0
阿里云服务器如何登录?阿里云服务器的三种登录方法
购买阿里云ECS云服务器后如何登录?场景不同,阿里云优惠总结大概有三种登录方式: 登录到ECS云服务器控制台 在ECS云服务器控制台用户可以更改密码、更换系.
12179 0
IG-REPORT企业智能报表 基于springboot+vue 轻松实现30s出报表
传统报表方式的弊端 报表是所有企业都必要的分析决策工具,传统的展示报表的方式特别麻烦,还记得两年前我入职的时候,领导让我做一个报表,步骤大概要经历1、数据库中创建一个目的表 存储SQL跑批后的结果 2、开发后端代码 从service到dao层都要开发 还要实现定时调度 3、开发前端代码 htmlcssjqueryajax等这些步骤从技术的角度来看算简单的、但却永远在做重复的事情。
1977 0
+关注
熊哥club
java,前端相关专家
68
文章
4
问答
文章排行榜
最热
最新
相关电子书
更多
《2021云上架构与运维峰会演讲合集》
立即下载
《零基础CSS入门教程》
立即下载
《零基础HTML入门教程》
立即下载