Objective
Speaking of Java reporting tools, I have touched only finereport (sail soft) and jasperreports, both of which are used, the sail soft is charged and jasperreports is free, first of all, the first feeling of the soft powerful sail, support the export of rich report format, But a lot of pits (a lattice of property settings not the entire report will be confused, such as Zovig, and sometimes a small number of data testing is no problem but the data volume of a big report on the mess, whatever the cause, first of all, this directly leads to not easy to find the problem, last year, after the project went online after the pit once), Again to talk about JasperReports, open source free, use aspects and sail soft ratio is not as strong as it, can not guide Excel, usually only used to guide the PDF, but in most cases can still meet the demand, after all, free can not ask too high ha, so, This blog summarizes the use and details of jasperreports and ireport.
Download ireport
The address is as follows:
Http://community.jaspersoft.com/download
We can see that the official most recent visual report design tool is Jaspersoft Studio (Eclipse-based), Early ireport from 5.5 after the update is no longer available, but has been using the ireport Development Report so this blog is based on ireport this tool for development, personal feeling is very good use (Lenovo to use Eclipse to develop Android kill not to change Android Studio t_t), we can download the ireport designer visual editor directly, as shown in:
Of course, there must be a jasperreports library to invoke the report through the Java program, because it is just a jar package so I upload directly to csdn for everyone to download, I use the version is jasperreports-5.6.1,:
http://download.csdn.net/detail/wlwlwlwl015/9509567
After downloading the installation, you can use it to create a report file.
Create a report
Open ireport, click File –>new, you can see a new file panel:
You can see the menu on the left provides a variety of report chart types, because we mainly do the basic report so we only focus on the report, and the right side provides some templates, such as Portrait A4, horizontal A4, etc., usually we use the most is the first vertical A4, select it and click on the "Open this Template, which will then pop up the naming and positioning panel, enter the name of the registration file and the directory where the file is stored:
Finally click Finish to enter the editing interface of the report:
Edit Report
First, let's look at the main interface of ireport:
is a set of standard editing interface, the left side is the Inspector area, the middle is the main editing area, the upper right is the palette area (if not through the CTRL+SHIFT+8 key combination), the lower right is the property window, the bottom is the output area, the left is problem Window (error), the Output window on the right, and the DB connection Settings area below the menu bar. First we look at the main editing area:
For example, ireport a report as the way to split, as the name implies that different areas should be placed different content, the operation of the words and C # to do the WinForm program feel similar, is to drag the control! Set Properties! Here we give an example of a performance report, the first is the title, general static text we unified with the component panel in the static text (lable), such as:
Title
Note that the two most commonly used components here are the static text and the text field below, which is usually used for static texts, such as headings, column names, and so on, while text field is typically used to put dynamic expressions, such as database query results, functions, and so on. Drag the static text from the palette to the title of the edit area below:
The top row of toolbars lets you set the alignment of component content, font styles, and so on, but in many cases we'll set these up in the Properties panel:
About properties It is very important to set the report font and encoding, slide the properties panel to the bottom to see these two properties:
For example, since our title is Chinese, we must set it to Chinese font and encoding:
- Stsong-light
- Unigb-ucs2-h (Chinese Simplified)
Only in this way can we display Chinese correctly in the report, including all subsequent controls that contain Chinese.
Page Header
The title is very simple, next is the page header, we can put some common properties on the page, such as: School, class information, and so on, as shown:
We put the school, class, and time in the page header, we can see that we used 6 controls, 3 static text and 3 text Filed, as we said before, static text is used to put the literal, and the text Filed to put the dynamic expression , the school and the class we found in the db (in detail later), and time here is done with a dynamic expression, such as:
About expressions (expression) is a topic worthy of further study, and ireport provides us with many types of expressions, such as:
Here we see the Java code that we are very familiar with, and the Java language is the first language that ireport officially recommends (although the groovy, JavaScript-language expressions are also supported):
ireport provides us with a rich expression syntax that can be seen even including three-mesh expressions, allowing us to easily perform related operations, such as setting the specified format time and outputting:
This allows us to display the current time in the report in the specified format.
Column Header
After reading the page header, next is the column header, this area will usually put the header, so it should also be static text, the table of this report I did not use the table control to do, but through a number of static text and text field of the table, As shown in the following:
ireport's own drag snaplines make it easy to drag and drop controls to the right place, including resizing them, or by CTRL + left mouse button to select multiple controls to set consistent property values for them, about static text or text Field borders (border) need to be noted, because they are not found in the properties panel, we need to select the control and then right-click in the Popup "Padding and Borders" to set the border, as shown in:
We click on the 4 edges in borders, then set line width to 1, and now we can see the border:
Create DataSource
To this end, all the static content of our report is basically finished, and then the main dynamic generated part, because the project's persistence layer adopts the MyBatis framework, so here we use SQL as query language. First you need to confirm the data source, at the beginning of the location of the DB data source settings, click on this icon:
We will then see the following window:
You can see that is the panel used to create the data source, the first two are ireport in advance to create an empty data source and a sample data source, the 3rd is I have created a good, I am here to re-create a new data source, click New:
You can see that there are very rich data source types available, such as JDBC, Hibernate, EJB, and so on, because the persistence layer in my project is using the MyBatis framework, so select the first--database JDBC connection here, Then click Next:
Obviously, choose JDBC Driver and enter the URL, username and password, then click Test, if the prompt is successful, then our data source will be able to write the query statement of the report if it is successfully created.
Report Query
First we need to know where to enter the query SQL and click on the button as identified:
You can then see the query window:
For example, after we tick automatically Retrieve fields, we will automatically retrieve all the columns of the query results after we have entered the SQL statement, and we can see a preview of the data at the bottom:
In this case, the query SQL for the report is completed successfully, we finally placed each in the report Detail 1 area in the text field according to the column name.
Detail 1
Yes, this area is the main data display area of the report, first drag and drop the text field into the Detail 1 area and align with the column header, then set the border, the effect is as follows:
You can see that each text field has a default value $F {field}, what does this mean? We can find the answer in the official documentation:
Yes, $F is referring to the meaning of a field (field), What is fields? Obviously, we just wrote that each column of query results returned by the query SQL statement is a field, which we can also see in the Inspector area on the left:
With these concepts the next question is simple, and we just need to modify each of the text field's expressions according to field name, for example, to modify the Ticket Number column:
Here's a quick look at the changes:
There are a few points that need to be emphasized:
- The 1th and most important point has been marked, that is, the height of the detail 1 area is consistent with the row height of the text field, so there is no line spacing when the loop line generates the report.
- All text field or static text containing Chinese will need to be uniformly set in Chinese font (stsong-light) and Chinese encoding (unigb-ucs2-h (Chinese Simplified)).
- Since we did not use the table component but the form of a text field, it is best to zoom in and look at the border details and alignment details, and so on:
- Uniformly sets the content alignment for all text field and static text, preferably horizontally centered () and vertically centered ().
- Another detail to note is that if the SQL statement query is empty, then the default is to display nullin the report, so it is not very attractive, but the solution is simple, which is to set all possible empty values of the lattice (Text Field) to blank When NULL, which is NULL when replaced with an empty lattice:
- Finally, you should preview the report effect in ireport and click Peview to enter the Preview view:
Then you can see the preview of our report:
Overall is perfect! Note the ireport Output window at the bottom of the preview, and you can see this message:
Yes, the source file Report1.jrxml was compiled and generated a report1.jasper file, in JasperReports, Jrxml is the source file, and can run the source file compiled Jasper file. We will automatically compile the preview, of course, while writing the source file, we can also compile manually, the compile button here:
Back to look at the preview of the report, notice that the serial number of this column is messed up, because our SQL is in accordance with the ticket number ASC ascending order, so with Oracle RowNum do the ordinal as if some inappropriate, but it doesn't matter, ireport also comes with a similar serial number function! We do this by adding variables (Variables). First we need to create a new variable, find variables in the Inspector area on the left and new one variable named RowNumber:
About variables (Variables) We can find instructions for it in Chapter 6 of the official documentation:
First we define the type of this variable as Java.lang.integer,caculation set to Count,reset type set to report:
You can see that the reset type is set to report when the variable is initialized only 1 times, and is using the value of intital value expression as the initial value, then we set intital value expression to 1, such as:
Finally, set the variable expression (Variable expression) to $V {rownumber}.valueof (1) . Now change the text Filed of the ordinal, change the original reference field to the reference variable RowNumber, and then preview it again to see the effect:
You can see the serial number can be displayed properly! Now that our report section is complete, let's look at how to invoke the report in a Java program.
Java Invoke report
and sail soft Finereport Some differences, sail soft is the report server servlet encapsulated in the jar package we only need to reference in Web. XML, but jasperreports need us to write, the idea is the same, look directly at the code:
Package Net. Xnzz. servlet;Import Java. IO. File;Import Java. IO. IOException;Import Java. SQL. Connection;Import Java. Util. Enumeration;Import Java. Util. HashMap;Import Javax. servlet. ServletContext;Import Javax. servlet. Servletexception;Import Javax. servlet. Servletoutputstream;Import Javax. servlet. HTTP. HttpServlet;Import Javax. servlet. HTTP. HttpServletRequest;Import Javax. servlet. HTTP. HttpServletResponse;Import Net. SF. JasperReports. Engine. Jrexception;Import Net. SF. JasperReports. Engine. Jasperrunmanager;Import Net. Xnzz. Util. Dbutils;public class Jrpdfservlet extends HttpServlet {private static final long Serialversionuid =1L;public void Service (HttpServletRequest request, httpservletresponse response) throws Servletexception, ioexcept Ion {Connection Connection = dbutils. Getdbinstance(). Getinitdbconnection();try {//According to Jasper file generated Jasperprint Object ServletContext context = This. Getservletconfig(). Getservletcontext();String FileName = Request. GetParameter("FileName");//ireport compile file: *.jasper (generated by template file *.jrxml file compilation)File Reportfile = new File (context. Getrealpath("/web-inf/jaspers/"+filename));hashmap<string, object> parameters = new hashmap<string, object> ();//parameter to report template fileGets the parameter name of the enumeration type, the parameter name if duplicate can only get the first--get the parameter that comes from the page, and the SQL parameter name of the file in the template one by one corresponds to enumeration<?> temp = Request. Getparameternames();while (temp. hasMoreElements()) {String paramname = (String) Temp. Nextelement();String paramvalue = Request. GetParameter(paramname);Parameters. Put(ParamName, Paramvalue);} byte[] bytes = Jasperrunmanager. Runreporttopdf(Reportfile. GetPath(), parameters,connection);Response. setContentType("Application/pdf");Response. Setcontentlength(bytes. Length);Servletoutputstream out= Response. Getoutputstream(); out. Write(Bytes,0, bytes. Length); out. Flush(); out. Close();} catch (Jrexception e) {E. Printstacktrace();} }}
The idea is simple, is to read the compiled. Jasper file in the project through the IO stream, and then output a report file in PDF format to the client via Jasperrunmanager, so that the servlet can be used for all jasperreports, because of the parameter and file name, etc. Use. Server-side code is finished, and then look at how the client calls the report, look at the following JSP code:
<body> <iframe id="Reportframe" width="100%" height="88 % " frameborder=" No " border=" 0 " marginwidth=" 0 " marginheight= "0" scrolling= "no" allowtransparency=" Yes "></iframe></body><script type="Text/javascript"> function getsearch() {var path = "${ Pagecontext.request.contextpath}/servlet/jrpdftyservlet?filename=report222.jasper " $ (" #reportFrame ") /c13>). attr ("src", path);
It's simple! I define an IFRAME here, just need to set the report servlet path to the src attribute of the IFRAME, of course, if the report has parameters, you can use the JS string concatenation and then string to the servlet address, so that all the work has been completed, Finally look at the report effect in the program. Google Chrome's effects:
The effect of IE browser:
Not bad ~ Such a report user whether it is printed or exported PDF is very convenient, about jasperreports introduction to this even if all the end, of course, this is only a general content, interested students can themselves through the official documents and further detailed study, Download official documents also to register JasperReports members, so I have downloaded the official documents here to upload to the csdn space:
Ireport-ultimate-guide.pdf
Summarize
Simply record the use of JasperReports and its visual report editor--ireport, hoping to help the students interested in this area, the End.
Java Report JasperReports & IReport