ireport製作jasperreport報表詳細過程(包括jsp端代碼實現)

來源:互聯網
上載者:User

概述:

現在簡要的介紹Jasperreport 是
如何工作的,這樣你可以更好的理解iReport 是如何協助Jasperreport 實現前端的
工作,其實這些工作在我們看來就是“髒活”,為什麼呢?看看下面的資料就知
道了:

首先是要有一個XML
檔案(一般是以jrxml尾碼),那麼這個XML檔案從那裡來呢?做什麼用呢? 這
個XML 檔案就是報表的定義檔案,整個報表的每一個細節都在這個XML 檔案
之中定義,一個簡單報表的xml檔案就有幾百行,你可以手工編輯這個XML文
件(一行一行,一段一段的編輯吧――這就是所謂的“髒活”),然後可以在jsp後台使用JasperCompileManager將xml檔案編譯為jasper檔案

ireport工具就是簡化編寫xml檔案和編譯的這個流程,而且提供可視化編輯視窗,非常方便

ireport部分:

我使用的是ireport3.0和現在最新的4.0介面上有很大的不同:

3.0介面:

 

這裡,我假設ireport的環境已經配置完畢,點擊左上方的檔案,選擇開啟新檔,設定報表初始化參數:

注意一下裡邊的欄位數的按鈕,欄位數設定預設為1,如果設定為2的話,就相當於每一列會有2個欄位排列,這樣講有點抽象,請看下邊

的例子:

假設我們的資料表是這樣:

name sex realname remark
a_1 b_1 c_1 d_1
a_2 b_2 c_2 d_2
a_3 b_3 c_3 d_3
a_4 b_4 c_4 d_4

如果ireport的欄位數設為2,結果會變成:

name sex realname remark
a_1 a_2 b_1 b_2 c_1 c_2 d_1 d_2
a_3 a_4 b_3 b_4 c_3 c_4 d_3 d_4

所以,一般設定欄位數為1即可。

建立後,可以看到中間的控制台:

這裡,假設您只需要報表顯示表格和統計資料,所以title和lastpagefooter可以不要,在左上方的預覽裡,選擇欄,把title和lastpagefooter高度設為0.

下面開始設計報表:

 

然後可以拖拉到控制台對應欄位對齊

這裡假設各位都會對其,如下:

使用報表變數,計算統計值:

document下右鍵添加variable,出現這個介面,然後按照這樣設定:

這裡我是統計列a的個行相加值,因為前面 已經設定了sum,所以,報表會自動計算資料行a的相加值。

這裡設計報表要注意幾點:

1.欄位間要對齊,方框為紅色的,表明是超出報表邊界

2.寫運算式的時候,與java類型相容,但是寫法有點不同,類型轉換要用new 類型  不然會報錯

jsp處理報表部分設定report環境:

1.每個Web應用都會有WEB-INF目錄,但是lib 是不一定有的,如果沒有就創
建它,本文需要的jar庫檔案有3個:
jasperreports-0.5.3.jar :jasperreports執行時需要的API
iTextAsian.jar :亞洲字元集支援
itext-1.02b.jar :其他字元集支援

2.在Web應用中根目錄下建立repotrs目錄,其實這是一種建議,沒有必要完
全按照這樣做,你可以根據你的業務需要建立N個目錄或是層次目錄。
把.jasper檔案拷貝到repotrs目錄下,比如例子中的BusinessRpt.jasper
檔案。

 

 

 

jsp兩種模式:

1.直接使用jsp處理報表

2.使用servlet處理報表

1.使用jsp處理報表:

jsp檔案:

<%@ page session="false" %><%@ page import="dori.jasper.engine.*" %><%@ page import="javax.naming.*"%><%@ page import="java.sql.*"%><%@ page import="javax.sql.*"%><%@ page import="java.util.*" %><%@ page import="java.io.*" %><html><head><meta http-equiv="Content-Type" content="text/html; charset=gb2312"><title></title><%DataSource ds = null;try{InitialContext ctx=new InitialContext();ds=(DataSource)ctx.lookup("java:comp/env/jdbc/mysql");Connection conn = ds.getConnection();//裝載jasper 檔案File business_rpt = newFile(application.getRealPath("/reports/BusinessRpt.jasper"));// http://blog.csdn.net/jemlee2002/archive/2004/10/08/JJem3.aspx//ProjectName 就是iReport 的變數$P{ProjectName}的名稱,//proname 就是從介面上擷取的值。Map parameters = new HashMap();parameters.put("ProjectName ", proname);// JasperRunManager是一個輸出控制管理類,下文會提及部分內容JasperRunManager.runReportToHtmlFile(business_rpt.getPath(),parameters,conn);//如果建立報表成功,則轉向該報表,其實可以把報表套在架構內,這樣實現比較有意義的報表格式。response.sendRedirect("/reports/BusinessRpt.html");}catch(Exception ex){out.print("出現例外,資訊是:"+ex.getMessage());ex.printStackTrace();}%></head><body></body></html>

2.使用servlet處理報表:

主要區別就是,servlet是直接輸出report報表流:

先寫一個CustomDataSource類實現report的JRDataSource介面,轉化vector向量為資料來源:

public class CustomDataSource implements JRDataSource{        private Vector dataVector = new Vector();private int index = -1;public CustomDataSource(Vector DataVector){           dataVector=DataVector;}public boolean next() throws JRException{index++;return (index < dataVector.size());}public Object getFieldValue(JRField field) throws JRException{         Object value = null; String fieldName = field.getName();             value=((Map)dataVector.get(index)).get(fieldName);return value;}}

輸出html:

ServletContext context = this.getServletConfig().getServletContext();File reportFile = new File(context.getRealPath("/reports/test.jasper"));//載入報表路徑if (!reportFile.exists()) {response.setContentType(CONTENT_TYPE);PrintWriter out = response.getWriter();out.print("<script language='javascript'>");out.print("alert('找不到報表!');");out.print("</script>");return;}Map parameters = new HashMap();response.setContentType(CONTENT_TYPE);PrintWriter out = response.getWriter();try {JasperReport jasperReport = (JasperReport) JRLoader.loadObject(reportFile.getPath());//載入報表/* java.lang.reflect.Field pageHeight = JRBaseReport.class.getDeclaredField("pageHeight");    pageHeight.setAccessible(true);    pageHeight.setInt(jasperReport, 500);*/JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters,new CustomDataSource((Vector) re.get(1)));//載入資料來源和parameters,這裡的資料來源用到的是JRDataSource,所以要實現JRDataSource介面JRHtmlExporter exporter = new JRHtmlExporter();Map imagesMap = new HashMap();request.getSession().setAttribute("IMAGES_MAP",imagesMap);String header = "";header = "<script language='javascript'>\n";header += "window.history.forward(1);\n";header += "document.onkeydown=function(){if(event.keyCode==8){if((document.activeElement.type!='text')&&(document.activeElement.type!='textarea')){event.keyCode=0}};}\n";header += "document.oncontextmenu=function() {return false;};\n";header += "</script>\n";header += "<html>\n";header += "<head>\n";header += "  <meta http-equiv=\"Content-Type\" content=\"text/html; charset=GBK\">\n";header += "<style type=\"text/css\">\n";header += "    a {text-decoration: none}\n";header += "  </style>\n";header += "</head>\n";header += "<body text=\"#000000\" link=\"#000000\" alink=\"#000000\" vlink=\"#000000\">\n";header += "<table width=\"100%\" cellpadding=\"0\" cellspacing=\"0\" border=\"0\">\n";header += "<tr><td width=\"50%\">&nbsp;</td><td align=\"center\">\n";header += "\n";exporter.setParameter(JRExporterParameter.JASPER_PRINT,jasperPrint);exporter.setParameter(JRExporterParameter.OUTPUT_WRITER, out);exporter.setParameter(JRHtmlExporterParameter.IMAGES_MAP,imagesMap);exporter.setParameter(JRHtmlExporterParameter.IMAGES_URI,"/Images/");exporter.setParameter(JRHtmlExporterParameter.HTML_HEADER,header);exporter.exportReport();
pdf輸出:
byte[] bytes = null;try {bytes = JasperRunManager.runReportToPdf(reportFile.getPath(), parameters,new CustomDataSource((Vector) re.get(1)));if (bytes != null && bytes.length > 0) {response.setContentType("application/pdf");response.setContentLength(bytes.length);ServletOutputStream ouputStream = response.getOutputStream();ouputStream.write(bytes, 0, bytes.length);ouputStream.flush();ouputStream.close();}} catch (Exception e) {e.printStackTrace();System.out.println("ErrorTime:" + new Date());response.setContentType(CONTENT_TYPE);PrintWriter out = response.getWriter();out.print("<script language='javascript'>");out.print("alert('"+ e.toString().replace("'", " ") + "');");out.print("</script>");}
excel輸出:
try {JasperReport jasperReport = (JasperReport) JRLoader.loadObject(reportFile.getPath());ServletOutputStream ouputStream = response.getOutputStream();JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters,new CustomDataSource((Vector) re.get(1)));response.setContentType("application/ms-excel");response.setHeader("Content-Disposition","inline;filename=\""+ jasperPrint.getName() + ".XLS\"");JRXlsExporter exporter = new JRXlsExporter();exporter.setParameter(JRExporterParameter.JASPER_PRINT,jasperPrint);exporter.setParameter(JRExporterParameter.OUTPUT_STREAM,ouputStream);exporter.setParameter(JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS,Boolean.TRUE);exporter.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET,Boolean.FALSE);exporter.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND,Boolean.FALSE);exporter.exportReport();}catch (Exception e) {e.printStackTrace();System.out.println("ErrorTime:" + new Date());response.setContentType(CONTENT_TYPE);PrintWriter out = response.getWriter();out.print("<script language='javascript'>");out.print("alert('"+ e.toString().replace("'", " ") + "');");out.print("</script>");}
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.