Step by step iReport + JasperReports (2): JasperReport Elementary Course

Source: Internet
Author: User
This article is intended to understand the IReport IDE itself and its basic usage. When learning, you don't need to implement all the examples in this article, as long as you understand it. The specific usage will be mentioned later, this article describes the download, installation, and interface of ireport, as well as the basic usage: connect to a mysql data source and design a simplified report.

This article is intended to understand the IReport IDE itself and its basic usage. When learning, you don't need to implement all the examples in this article, as long as you understand it. The specific usage will be mentioned later, this article describes the download, installation, and interface of ireport, as well as the basic usage: connect to a mysql data source and design a simplified report.



This article is intended to understand the IReport IDE itself and its basic usage. When learning, you don't need to implement all the examples in this article, as long as you understand it. The specific usage will be mentioned later, this article describes the download, installation, and interface of ireport, as well as the basic usage: connecting to a mysql data source and designing a simplified report, describes the basic steps for using the report in a Java program. Preview The report results, for example:


, Http: // www. Chuanjiang subaccount. cn.

In addition, I have Word electronic document format, if necessary, please contact me: asima127@gmail.com



1 download iReport

IReport is a visual report template design tool that allows you to easily design reports. The jasport contains the jar files required by jasperreports during runtime. The lib directory in the project contains Jasperreports -***. jar. *** indicates the version number, for example, 2.0.3.

: Http://sourceforge.net/project/showfiles.php? Group_id = 64348. This document is written in version 2.0.3,

Click download to display the following interface:

You can see that multiple download packages are provided, including:

? IReport-2.0.3-src.zip: source code for iReport

? IReport-2.0.3.tar.gz: For .tar.gz format, generally used for Linux, Unix and other non windows systems

? IReport-2.0.3-windows.installer.exe: exe format, generally used in windows

? IReport-2.0.3.zip: zip format for various operating systems

In this document, we use Windows as an example to download ireport-2.0.3-windows.installer.exe.

2 install iReport

To install iReport, you must first set the JDK environment. Version 2.0.X requires the JDK environment (for more information, see the documentation ).

In windows, double-click the installation icon. (If the ZIP file is downloaded, decompress it to the specified directory and runBin/startup. bat).

If it is another system, such as linux, unix, etc., extract the downloaded Installation File (such as the download is in the tar.gz format, using tar xvfziReport-2.0.3.tar.gz for decompression, such as the download zip format, using the zip command to decompress), and then runBin/startup. shYou can.

The following uses windows installation as an example:

A. On the welcome page, click"NExt> "continue

B. Read the license content and click "IAGree "continue

C. Select the installation component and click"NExt> "continue

D. Specify the installation path and click"NExt> "continue

E. Specify the group name and click"INstall"

F. Waiting for Installation

G. After the installation is complete, click"FInish completed

The following icon appears on the desktop :.

3. edit a Report Template

3.1 start iReport

Start the iReport-2.0.3,

The iReport will automatically set the Language based on the Locale attribute of the running machine. Here there may be some deviations. The author uses Simplified Chinese, but after the startup, the design interface is traditional Chinese, therefore, we need to set it.

3.2 set the default language

Toolbar-> "tool" (or"OPtion ")->" select"

Change the language type and select "Chinese" from the menu )". If this option is enabled, You can first change it to another type (such as "Chinese"), and then enter this interface again to change it to "Chinese (China )".

Click "Save Chinese", and the interface becomes "simplified Chinese ":

3.3 other settings

This step is not required. Set it as needed.

The newly created Report Template Using iReport is in. jrxml format. After editing, it needs to be compiled. The. jasper file will be generated during compilation, and the. jasper file needs to be compiled during runtime. This principle is similar to a java program. The source code file is. java. After compilation, It is a. class file. Only the. class file is required for the application.

After installation, the. jasper file is generated by default in the current directory. For ease of management, you can set the iReport design software and unify the directory to save the compiled jasper file.

IReport can be used to preview reports (pdf, excel) in multiple ways. If you select these formats during each preview, these files will be generated and can be saved in a unified manner through this setting.

"OPtion "->" option ", and then select" Compiler "on the tab to set" Default compilation directory "and" Directory where the paged out data is stored, click Browse next to it to select a directory.

If you do not want to save automatically generated java files during compilation, you can remove the check box before "keep. java file.

3.4 create a report template Sample

A. Choose toolbar> archive> enable new archive"

B. Enter the report name. This document is "sample". Click "OK" to continue.

C. Interface

, You can see the Report Template body is divided into several areas, the interpretation is as follows:

?Title

The title segment is only displayed on the top of the first page of the entire report. Except for the first page, NO content in the title segment is displayed no matter how many pages there are in the report.

?PageHeader

The content in the pageHeader segment will appear on every page of the report, and will be displayed on the top of the page. If it is the first page of the report, the content in pageHeader is displayed under the title segment. The content in pageHeader is displayed at the top of the page except for the first page.

?ColumnHeader

For the header segment of the detail segment, the column title in the table is usually illustrated in this segment. Each page appears.

?Detail

The report content section. In this section, you must design the content that needs to be repeated in the report. The content in the detail section appears on each page.

?ColumnFooter

For the table ending segment of the detail segment, each page will appear once.

?PageFooter

Display at the bottom of the page. Each page is displayed. The last page is replaced by lastPageFooter.

?LastPageFooter

The content at the end of the last page appears only once on the last page.

?Summary

The aggregate segment of the table appears after the detail segment on the last page of the entire report. It is generally used to count the total values of one or more fields in the report.

D. Create a database-type JDBC Data Source

IReport supports multiple databases. In this example, mysql is used as an example.

"DAta "->" link/resource source"

On the Connections/Datasources page, click New"

Select "DatabaseJDBC DBC connection" in "Connections properties" and click "Next" to continue. here we can see that the jasperreport data source can be in many ways: databases, XML files, and JavaBean files, it can be seen from this.

E. Specify the JDBC Type and jdbc url of the database.

The iReport contains the driver jar files of the mysql and hsqldb databases. You can select different JDBC types as needed, (copy the corresponding JDBC driver jar file to the lib directory of the project)

Enter the jdbc url and user name and password based on the actual content.

After entering the information, click"TExt. If the following interface is displayed, the connection is successful.

Click"SSave, you can see the configuration of this connection in the list

F. Set REPORT query

Tool bar "Data"-> "REPORT query"

The following page is displayed:

You can see that there are multiple data sources. Here we use the Report Query method. In this way, you can directly select the Query Lanuage type, and then enter the SQL statement in the editing box.

For example, select * from employee will automatically read the structure of the relevant table,

Click"OK, the Field names of these tables will be added to the "Fields" section of "Document structure,

Here, you can also use another method, that is, to introduce parameters, so that you can flexibly set parameters to change the data content during the call according to business rules:

Find "Parameters" in the "Document structure" area, right-click it, and select "Add ...", Then select "Parameter ",

Enter the following content. ParameterName can be used in the Report query interface or in your own business logic. You can change it. Here you can also give a Default value, that is, the content of Default ValueExpression, pay attention to the Parameter Class Type. In this example, the default java. lang. string

This parameter is specified in the report query editing content in the format of "$ P! {ParameterName} "," $ P! is used in this example! {SQLSTR} ". After the input, the table structure will be automatically updated. Click" OK "and place the table structure content in the" Fileds "area.

G. edit a Report Template

In the editing area, place the required elements in the corresponding segments. There are many elements, which are commonly used in the following types:

? Static text content: the content is a fixed text content, such as the "Test Report"

? Parameter (Parameter): for example, "$ P {SQLSTR }"

? Field (Fields): for example, "$ F {EMPLOYEE_ID }"

? Variable (Variables): for example, "$ V {PAGE_NUMBER }"

Drag the required content to the template editing area.

In the corresponding segment.

H. Compile and preview

On the toolbar, find, compile, execute, and execute (Dynamic Link). Click compile to generate. in the jasper file, click execute to compile the file before previewing (if the corresponding preview is set ).

You can preview multiple methods by clicking "CREATE" on the toolbar. You can see the following preview methods:

Select the preview type as needed. Note that if no corresponding software (such as Adobe Reader) is available to view the generated files, the results will not be displayed, the iReport will generate files in the corresponding directory (see section 3.3 ).

How to set the File Viewing software, or click "Op" on the toolbarTIons "->" option ", select" External Programs "on the tab, and select the corresponding viewing software for each format to be set,

In this way, the preview file type is specified, and the preview software is specified. When you click preview, the corresponding preview is used.

I. Preview results

J. Report Template created

4. Use iReport in Web

4.1 development tools

The development tool works with eclispe3.2.2 and MyEclipse5.0. For environment configuration, refer to other manual.

4.2 create a project

Open Eclipse, and in the toolbar,FIle "->"NEw "->"OTher"

Create a web Project, select "Web Project" under "MyEclipse", and click"NExt "next step,

Enter the Project Name. In this example, enter "iReportTest" and click"FInish completed

The iReportTest project is displayed in the project list:

4.3 import jar files

In the project, find "WebRoot"-> "lib", right-click, and select"IMport ...",

Select "General"-> "File System" and click"NExt "continue

Click "B ".ROwse ...", Specify the jar file. Here, beginners can point to all the jar files in the lib directory under the Jasper installation directory, so that you can quickly see the effect and exclude the txt files.

In the project, we can see that the jar file has been introduced,


4.4 import the jasper File

Create a directory report under WebRoot and import the jasper file compiled in section 3.4.

4.5 process reports with Chinese characters

When a PDF file is created, the Chinese content may not be displayed. Note the following when setting the font:

1. The Font Name of the Font to be set must display Chinese characters, such as and SansSerfi.

2. Set the PDF Font Name To STSong-Light.

3. Set PDF Encoding As UniGB-UCS2-H (Chinese Simplified)

4. Whether lib contains the iTextAsian. jar File

Right-click the content of the Font you want to change, select "properties", and select "Font" on the tab to make changes:

PDF preview:

4.6 unified font attribute settings

In the previous section, we set each font box. If we need to set 100 fonts, it will be cumbersome to set them one by one, reducing the efficiency.

IReport provides a function to configure this setting, and then select it as needed. In the toolbar, choose "format"> "Style" (2.0.3 is recommended, if the earlier version is "font "),

Click "New" to create a New format, name it "", and then perform relevant settings,

In this way, the Style of the "" is set. When setting the font, you do not need to go to the tab one by one. Select the "Common" tab in the font attribute, select this "" in the Style:

4.7 create a JSP file that displays HTML reports

Create the jsp file testhtml. jsp In the WebRoot root directory. The content is as follows:

<% @ Page contentType = "text/html; charset = GB2312" %>

<% @ Page import = "net. sf. jasperreports. engine. *" %>

<% @ Page import = "java. util. *" %>

<% @ Page import = "java. io. *" %>

<% @ Page import = "java. SQL. *" %>

<%

// Storage location of the. jasper file generated after the report is compiled

File reportFile =NewFile (This. GetServletContext (). (1)

GetRealPath ("/report/sample. jasper "));

String url = "jdbc: mysql: // localhost: 3306/db ";

Class. forName ("com. mysql. jdbc. Driver ");

Map parameters =NewHashMap ();

// "SQLSTR" is the parameter name defined in the report. Its type is String type.

// Set the content of the sqlstr parameter and assign values to the SQL statement as needed

Parameters. put ("SQLSTR", "select * from employee"); (2)

Connectionconn = DriverManager. getConnection (url, (3)

"Username", "password ");

JasperRunManager. runReportToHtmlFile (reportFile. getPath (), (4)

Parameters, conn );

Response. sendRedirect ("report/sample.html"); (5)

%>

Code Description:

1. Locate the jasper File

2. assign values to the SQLSTR parameter used in the Report Template. An SQL statement is specified here.

3. Use JDBC to connect to the database

4. Generate HTML files. The parameters are the physical location of the report file template, report parameters, and database links.

5. Go to this page. The page is fixed and must be in the same location and path as the report template.

After the project is published, preview the project and enter http: // localhost: 8080/iReportTest/testhtml. jsp (in this example, tomcat is used as the web server. For details about the release process, refer to other documents and use mysql as the database)

Effect:

4.8 Create a JSP file that displays reports in PDF Format

Create the jsp file testpdf. jsp In the WebRoot root directory. The content is as follows:

<% @ Page contentType = "application/pdf; charset = UTF-8" %>

<% @ Page import = "net. sf. jasperreports. engine. *" %>

<% @ Page import = "java. util. *" %>

<% @ Page import = "java. io. *" %>

<% @ Page import = "java. SQL. *" %>

<%

// Storage location of the. jasper file generated after the report is compiled

File reportFile =NewFile (This. GetServletContext ().

GetRealPath ("/report/sample. jasper "));

String url = "jdbc: mysql: // localhost: 3306/db ";

Class. forName ("com. mysql. jdbc. Driver ");

Map parameters =NewHashMap ();

// "SQLSTR" is a parameter name defined in the report. Its type is String type.

Parameters. put ("SQLSTR ",

"Select * from employee where employee_id like 'z % '");

Connection conn = DriverManager. getConnection (url,

"Username", "password ");

Byte[] Bytes = JasperRunManager.

RunReportToPdf (reportFile. getPath (), parameters, conn );

Response. setContentType ("application/pdf ");

Response. setContentLength (bytes. length );

ServletOutputStream outStream = response. getOutputStream ();

OutStream. write (bytes, 0, bytes. length );

OutStream. flush ();

OutStream. close ();

Out. clear ();

Out = pageContext. pushBody ();

%>

The effect is as follows:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.