JasperReport experience talks

xiaoxiao2021-03-06  107

JasperReport and Ireport are nice Java Report Tools. In the actual project, I have developed 20 Reports with them involved in Subreport, Image, Graph, accumulated some experience. Especially about export to Excel, there are very few documents. And, it is purely to explore, some problems are still solved by reading source code. This post is not entitled to the tutorial, and it is almost a note, in question and answer form.

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', do not count on $ p {a} can be replaced with '' value '' How to use chart (graph) JasperReport itself has no chart function, There is only a function of displaying Image (see 4.3). There is a graph wizard in Ireport, which is virtually generated by JFreeChart. More additional, more direct practices are to put an image control, Image Express class is set to java.awt.image, Image expression returns a Java.awt.Image object through a custom class. For example, '' graphprovider.getimage ($ P {report_datasource}, title, subtitle .....) ''. GraphProvider is your own class, public static image GetImage (JRDataSource, ....) If you display multiple charts

Display a chart and display a plurality of charts on a report. Suppose Query is Select Name, Price, Qty from xxx, the first picture shows name-price, the second picture shows Name-Qty, if still pressed 3.8 Method, the second picture is not shown here! Why is it because it is jrdatasource, and JRDataSource is just a simple package for ResultSet. After the first picture is processed, the cursor has reached the EOF position, start processing When the second picture, you will inevitably throw the exception of the cursor! How to do yourself write a JRDataSourceAdapter, save the value of the JRDataSource object to a Collection (equivalent to the data set of OFFLINE), then transfer this Collection a getImage method. specifically, a construction Variable mydate, type java.util.Map, Calculation Type- System, Initial Value Expression is JRDataSourceAdapter.JRDataSource2Map ($ P {REPORT_DATA_SOURCE}, new String [] { "NAME", "PRICE "," Qty "}, new class [] {java.lang.string.class, java.lang.double.class, java.lang.double.class}, JRDataSource2map is an adapter written by yourself. Then in Image Expression replaced with '' graphprovider.getimage (MyData, Title, Other Params ...), of course, GetImage methods 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 the parameters:. exporter.setParameter (JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, Boolean.TRUE); how to keep GridLine first, set the parameters exporter.setParameter (JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND, Boolean.FALSE); then, each Field or Static Text Box '' TRANSPARENT '' attributes 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 starts displayed

Because the first line and the column are used to represent Page Top Margin and Page Left Margin. For Excel, it is purely redundant. The solution is to set up margin 0. However, if this Report needs to display PDF. So, it is not good. It is best to dynamically change Page Margin. Of course, this change can only be performed outside (call Report), it is incompetent when designing Report. Unfortunately, JasperReport class Actually there is no setMargin method, only getter. Forte method can only be Reflect. Code is 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 travel in Excel, due to the relationship of Page Break, every part of Excel There are dozens of rows, there is a high value of 0, even if you set the page botom margin to 0, there is no way to remove Page Footer. The only solution is to set the Page Height to a big. Like 5.5, you have to Use Reflect:

Java.lang.reflect.field PageHeight = JRBASEREPORT.CLASS.GETDECLAREDFIELD ("PageHeight"); PageHeight.SetInet (TRUE); PageHeight.SetInt (MyRpt, Integer.max_Value); Document

Where is the document?

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 iLlegaArgumentException ("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

Map params = new hashmap (10); Enumeration Enu = Request.getParameterNames ();

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

转载请注明原文地址:https://www.9cbs.com/read-94411.html

New Post(0)