IREPORT installation
Download, unzip the IREPORT 0.4.0 (recommended SRC version) Confirm that JDK is 1.4 or more to copy the Tools.jar under JDK / LIB to the {Ireport_Home} / lib directory
For downloaded Binary versions, you can only run /bin/startup.bat for downloaded SRC versions, you can run through Ant Ireport (first install Ant) If you run Startup.bat, a java.lang.nosuchmethodeError error is generally a JDK version. low. If you confirm that 1.4 or more is installed, check the Path system variable, see if the JRE of 1.3 is not ranked in front (such as installed Oracle client, there is a 1.3 JRE), if the Class Not found, check the classpath. For operation through Ant, there is no problem, so I recommend download SRC version JASPERREPORT FAQ
.jrxml vs .jasper
If you load .jrxml at runtime, you have to compile each time, it is better to compile it into .jasper. However, pre-compiled Jasper, you must use the same version of JasperReport to load, and flexibility is different. But for most reports, Still compiling into JASPER, if you compile JRXML in batches
It is easy to solve with Ant
.....
How to use pictures?
It is easy to use the image control. You can use string to represent the path of the image in Image Express, or use the InputStream, File object. However, no matter whether it is still a String object, you have to use an absolute path, which is obviously unfunctuous. The solution is to wear a $ p parameter, indicating the directory where the picture is located, then splicing out the complete absolute path with $ P and file name. Better method is to use InputStream, such as this.getClass (). GetresourceAsStream. "), then you can put the picture in the current.jasper's directory, don't consider what parameters, what path shows non-database field variables
Displaying the date, etc., you can enter new java.util.date () directly in the Text Field, and then set the pattern as mm / dd / yyyy. Dynamically control some Field is displayed
Each Static Text, Text Field, even the entire Band's properties have Print When Expression, such as New Boolean (! $ P {isdisplay}. EqualsignoreCase ("YES"), then only when the value of the parameter Display is YES When you use Sub Report, how to use a relative path
See 1.3, and use the picture similar to how to use the parameters in inputStream or incoming parameter query
The latter can only be used to bind the pre previoustement parameter binding, while the former can replace any part of SQL. When you need to be dynamically sorted, the former is particularly useful. Such as SELECT A, B, c from t order by $ p! {Orderclause} No matter $ P or $ p !, SQL is ultimately executed in the preparedstatement method, do not have to worry too much performance problem Note: Parameters cannot nested, such as $ p}} = '' $ P {b} ', $ p {b} =' 'value', don't expect $ p {a} to be replaced with '' Value '' How to use Chart (Graph)
JasperReport itself has no chart function, only the function display image (see 4.3). There is a graph wizard in Ireport, which is generated by JFreeChart. More additional, more direct practices are an image control, Image Express class is set to Java .awt.image, returning a java.awt.image object in Image Expression. For example, '' graphprovider.getimage ($ P {report_datasource}, title, subtitle .....) ''. GraphProvider is yourself Class, Public Static Image GetImage (JRDataSource, ....) If you display a plurality of charts on a report and display multiple charts. Hypothesis Query is SELECT NAME, Price, Qty from xxx, A picture shows Name-Price, the second picture shows Name-QTY, if still pressing 3.8 method, the second picture does not display it at all! Why is JRDataSource just a simple package for RESULTSET After the first graph is processed, the cursor has arrived in the EOF position. When starting to deal with the second picture, you will inevitably throw the exception of the cursor, how to write a JRDataSourceAdapter, and put the value in the JRDataSource object. Pre-saved to a collection (equivalent to a data set of OFFLINE), then pass this Collection a getImage method. Specifically, build a variable mydate, type is java.util.map, Calculation Type- System, Initial value Expression is JRDataSourceAdapter .Jrdataserce2map ($ P {report_data_source}, new string [] {"name", "price", "qty"}, new class [] {java.lang.string.class, java.lang.double.class, Java. Lang.double.class}, jrdataasource2map is a Adapter written by yourself Then replace it in Image's Expression (MyData, Title, Other Params ...), of course, you have to modify the problem with GetImage method Export to Excel.
How to remove the report head, etc.
Directly delete unwanted BAND (set it to 0). If only export is only export to Excel, it does not need to be reported, and the output to PDF will still need to keep it, then use Print When Expression, see 4.4 If you let Excel Alliance
Don't have a blank place! First, put all the Field as high, align! Put the height of the BAND is also as high as Field, so that Field is placed in Band. Then adjust the width of the Field, so that each field is adjacent There is no gap. Finally, remember to set parameters: exporter.SetParameter (JRXLSEXPORTERPARETER.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, BOOLEAN.TRUE); How to keep gridline
First, set the parameter exporter.setParameter (JRXLSEXPORTERPARETER.IS_WHITE_PAGE_BACKGROUND, BOOLEAN.FALSE); then, how to make the field name only once
If you put the fields in the Columnhead area, then output to Excel, you will display each Page. When you design Report, you will usually set the page size. However, for Excel, this page setting still exists, and often hate, Because in Excel, it is often desirable to get continuous data, but Jasper will still '' 'self-satisfaction' 'for paging. For example, when designing JasperReport, set up size for letter, portrait, then output to Excel About 30 lines (depending on the Field height), Page header, column header, column foot, and page foot will be repeated once, and also with an Excel Row with a height of 0, which is placed in Page Break. In Title Band, you can solve the problem of repeated field name. Of course, Page Header is also displayed. If you need, you can set the Title Band's Print when Expression only Output Excel's data from the second line. The column B is displayed because the first row and the columns are used to represent the Page Top Margin and Page Left Margin. For Excel, it is purely redundant. Solution is to set up Page Margin 0. But if this Report also needs to be displayed in PDF, then it is not good. It is best to change the page margin. Of course, this change can only be performed outside (call Report), it is incompetent when designing Report. Unfortunately, the JasperReport class actually does not have setMargin method, only getter. Forte method can only be Reflect. The code is just as follows: // use reflect to set the private field of jrbasereport java.lang.reflect.field margin = JRBASEREPORT.CLASS.GETDECLAREDFIELD ("LeftMargin"); margin.setaccessible (true); Margin .setint (myrpt, 0); margin = jrbasereport.class.getDeclaredfield ("TopMargin"); margin.setAccessible (true); margin.setint (myrpt, 0); margin = jrbasereport.class.getDeclaredfield ("bottommargin"); Margin.setAccessible (TRUE); margin.setint (myrpt, 0); how to remove the hidden line in Excel
As far as Page Break's relationship, EXCEL is 10 rows, there is a high value of 0, even if it sets the page botom margin to 0, there is no way to remove Page Footer. Unique solution is Set Page Height to a big. Like 5.5, you have to use the reflect:
Java.lang.reflect.field PageHeight = JRBASEREPORT.CLASS.GETDECLAREDFIELD ("PageHeight"); PageHeight.SetIntible (TRUE); PageHeight.SetInt (MyRpt, Integer.max_Value); Where is the documentation?
JasperReport has a Ultimate Guide, but it is not free, and JFreechart is a virtue. However, there is a circulation on the Internet, it is ok, more than 60 pages, but not in detail. If you download the source code version, then take a look Demo is also good. SF Forum is also the best place source code for questioning only for reference only (ReportProvider - a servlet, graphproider, jrdataadapter is a common class)
/ ** *
Title: ReportProviderServlet
*
Description: servlet to generate Jasper Reports
*
Copyright: CopyRight (C) 2004
*
Company: *****
* @Author Zephyr
* @version 1.0
* /
Package XYZ;
Import net.sf.jasperreports.Engine. *; import net.sf.jasperreports.Engine.base. *; import net.sf.jasperreports.Engine.Export. *; import net.sf.jasperreports.Engine.util. *;
Import org.apache.log4j. *;
Import java.io. *;
Import java.sql. *;
Import java.util. *;
Import javax.servlet. *; import javax.servlet.http. *;
Public Class ReportProviderRVlet Extends httpservilet {private static logger log = logmanager.getlogger (ReportProviderServlet.class);
// Initialize: Setup DataSourceManager public void init () throws javax.servlet.ServletException {String prefix = getServletContext () getRealPath ( "/"); String file = getInitParameter ( "data-source-file");.
DataSourceManager.configure (prefix file);
LOG.INFO ("Initialized SuccessFully!");
// Process the HTTP request public void service (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {String reportClass = request.getParameter ( "reportClass");
Log.debug ("Running Report:" ReportClass);
Boolean ISEXCELFORMAT = false; if (reportClass == null) {throw new illegalgumentException ("jasper class unspecified");}
String reportFormat = Request.getParameter ("ReportFormat");
IF (ReportFormat == Null) {reportformat = "jasperprint";
Try {jasperreport myrpt = jaspermanager.loadReport (this.getclass () .getResourceceAsStream ("/ jasperreports /");
// set reprintheaderoneachpage = false for excel format ISEXCELFORMAT = ReportFormat.EqualsignoreCase ("Excel");
if (isExcelFormat) {// use reflect to set the private field of JRBaseReport // No margin for excel format, max pageHeight java.lang.reflect.Field margin = JRBaseReport.class.getDeclaredField ( "leftMargin"); margin.setAccessible ( True); margin.setint (myrpt, 0);
Margin = JRBASEREPORT.CLASS.GETDECLAREDFIELD ("TopMargin"); margin.setAccessible (TRUE); margin.setint (myrpt, 0);
Margin = JRBASEREPORT.CLASS.GETDECLAREDFIELD ("bottommargin"); margin.setAccessible (true); margin.setint (myrpt, 0);
Java.lang.reflect.field PageHeight = JRBASEREPORT.CLASS.GETDECLAREDFIELD ("PageHeight"); PageHeight.Setint (myrpt, integer.max_value);
// Don't Print Group Header on Each Page IF (NULL! = Myrpt.getGroups ()) {for (int i = 0; i While (Enu.haASMoreElements ()) {string key = (string) ENU.NEXTELEMENT (); params.put (key, request.getParameter (key) .touppercase (). ReplaceAll ("'", "' '")) Log.debug (Key "=" Request.GetParameter (key)); Log.debug ("Before Filling"); OutputStream httpout = response.getOutputStream (); Connection conn = DataSourceManager.getConnection (Request.GetSession ()); JasperPrint RPTPNT = JasperManager.FillReport (MyRpt, Params, Conn); CONN.CLOSE (); if (reportFormat.equalsIgnoreCase ( "jasperPrint")) {response.setContentType ( "application / octet-stream"); JRSaver.saveObject (rptPnt, httpOut);} else if (reportFormat.equalsIgnoreCase ( "pdf")) {response. setContentType ( "application / pdf"); response.setHeader ( "Content-Disposition", "attachment; filename = /" " reportClass " .PDF / ""); JasperManager.printReportToPdfStream (rptPnt, httpOut);} else if (ReportFormat.EqualsignoreCase ("excel")) {response.setContentType ("Application / VND.MS-Excel"); response.setHeader ("Content-Disposition", "Attachment; FileName = /" ReportClass ".xls / "" "; JRXLSEXPORTER EXPORTER = New JRXLSEXPORTER (); exporter.setParameter (JRExporterParameter.JASPER_PRINT, rptPnt); exporter.setParameter (JRExporterParameter.OUTPUT_STREAM, httpOut); 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 ();} else if (reportFormat.equalsIgnoreCase ( "html")) {JRHtmlExporter exporter = new JRHtmlExporter (); response.setContentType ( "text / html"); Map imagesmap = new hashmap (); Request.getations (). SetaTribute ("iMages_map", ImageSmap; exporter.setParameter (JRHtmlExporterParameter.IMAGES_MAP, imagesMap); exporter.setParameter (JRHtmlExporterParameter.IMAGES_URI, "image.jsp image ="); exporter.setParameter (JRExporterParameter.JASPER_PRINT, rptPnt); exporter.setParameter (JRExporterParameter.OUTPUT_STREAM, httpOut); Exporter.exportReport (); Log.debug ("Report Exported");} catch (exception ex) {log.error ("Error Occured, EX);}}} / ** * Title: JRDataSourceAdapter * Description: Converting JRDataSource to mapped arraylist * Copyright: CopyRight (C) 2004 * Company: ***** * @Author Zephyr * @version 1.0 * / Package XYZ; Import net.sf.jasperreports.Engine. *; import net.sf.jasperreports.Engine.Design. *; Import java.util. *; public class jrdataserceadapter {public static map jrdataserce2map (JRDataSource Datasource, String [] FieldNames, Class [] FieldClasses) throws jrexception {hashmap results IF (FieldNames.Length! = FieldClasses.Length) {Throw new jrexception ("Number of Field Name & Class Unmatch);} Jrdesignfield [] fields = new jrdesignfield [FieldNames.Length]; Result = new hashmap (4); For (int i = 0; i Do {for (int i = 0; i Return result;}} / ** * Title: GraphProvider * Description: Generate Jfreechart Image * Copyright: CopyRight (C) 2004 * Company: **** * @Author Zephyr * @version 1.0 * / Package XYZ; Import net.sf.jasperreports.Engine. *; import net.sf.jasperreports.Engine.design. *; import net.sf.jasperreports.Engine.Export. *; Import org.jfree.Chart. *; import org.jfree.chart.axis. *; import org.jfree.chart.plot. *; Import org.jfree.data. *; Import java.awt. *; import java.awt.image. *; Import java.io. *; Import java.util. *; public class GraphProvider {public static Image getImage (Map dataSource, String fieldNameX, String fieldNameY, String chartName, String titleX, String titleY, boolean isBarChart, int imageWidth, int imageHeight) throws JRException {JRDesignField fieldX = new JRDesignField (); fieldX.setName (FIELDNAMEX); Fieldx.SetValueClass (java.lang.string.class); JRDESIGNFIELD FIELDY = New JRDESIGNFIELD (); FIELDY.SetName (FieldNamey); Fieldy.SetValueClass (java.lang.double.class); ArrayList Periods = (arrayList) DataSource.get (FieldNamex); ArrayList Values = (arraylist) DataSource.get (FieldNamey); DEFAULTCATEGORYDATASET CATEGORYDS = New DefaultcategoryDataSet; For (int i = 0; i IF (Obj! = null) {datavalue = ((double) obj) .doublevalue ();} CategoryDs.AddValue (DataValue, Null, (String) Periods.get (i)); JFreeChart C = NULL; if (isBarChart) {c = ChartFactory.createBarChart (chartName, titleX, titleY, categoryDs, PlotOrientation.VERTICAL, false, false, false);} else {c = ChartFactory.createLineChart (chartName, titleX, titleY, categoryDs, PlotOrientation.VERTICAL , False, False, False; C. GetTitle (). setFont (New Font ("Arial", Font.Bold, 16)); Numberaxis axis = (numberaxis) c.getcategoryPlot (). GetRangeaxis (); Axis.SetAutoRange (TRUE); Tickunitsource tickunits = numberaxis.createintegertickunits (); Axis.setstandardTickUnits (TickUnits); Return (c.createBufferedImage (imagewidth, imageheight);}}