Detailed process of creating a jasperreport report by ireport (including JSP code implementation)

Source: Internet
Author: User

Overview:

The following is a brief introduction to jasperreport:
How to work, so that you can better understand how jasport helps jasperreport implement front-end
In fact, these jobs are "dirty" in our opinion. Why? Take a look at the following information.
Now:

First, you must have an XML
File (generally with the jrxml suffix), where does this XML file come from? What is the purpose? This
An XML file is the definition file of the Report. Every detail of the entire report is stored in this XML file.
The XML file of a simple report contains hundreds of lines. You can manually edit this XML file.
(One row, one row, and one segment to edit-this is the so-called "dirty"), and can be used in the JSP background.Jaspercompilemanager compiles XML files into Jasper files

The ireport tool simplifies the process of writing and compiling XML files, and provides a visual editing window, which is very convenient.

Ireport:

I use ireport3.0, which is very different from the latest 4.0 interface:

3.0 interface:

 

Here, I assume that the ireport environment has been configured. Click the file in the upper left corner, select enable new file, and set the report initialization parameters:

Note that the number of fields is set to 1 by default. If it is set to 2, two fields are arranged in each column, which is a little abstract, see below

Example:

Suppose our data table is like this:

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

If the number of fields in ireport is set to 2, the result will be changed:

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

Therefore, set the number of fields to 1.

After creating the dashboard, you can see the central control panel:

Here, if you only need to display tables and statistical data in the report, you can choose title and lastpagefooter. In the preview in the upper left corner, select the bar and set the height of title and lastpagefooter to 0.

Design the report as follows:

 

Then, you can drag it to the control panel to align the corresponding fields.

Here, we assume that you will treat it as follows:

Use report variables to calculate the statistical value:

Right-click under document to add variable. This interface is displayed, and then set as follows:

Here I calculate the sum of rows in column A. Because sum has been set before, the report automatically calculates the sum value of column.

Pay attention to the following points when designing reports:

1. The fields must be aligned. The box is red, indicating that the boundary of the Report is exceeded.

2. When writing an expression, it is compatible with the Java type, but the writing method is a little different. type conversion should use the new type. Otherwise, an error will be reported.

In the JSP processing report section, set the report environment:

1. Each web application will have a WEB-INF directory, but Lib is not necessarily there, if there is no
Create it. Three jar files are required in this document:
Jasperreports-0.5.3.jar: the API required for jasperreports execution
Itextasian. jar: supported Asian character sets
Itext-1.02b.jar: supported by other character sets

2. Create the repotrs directory under the root directory of the Web application. In fact, this is a suggestion and it is not necessary.
You can create n directories or hierarchical directories based on your business needs.
Copy the. Jasper file to the repotrs directory, for example, businessrpt. Jasper in the example.
File.

 

 

 

Two JSP modes:

1. Use JSP to process reports directly

2. Use servlet to process reports

1. Use JSP to process reports:

JSP file:

<% @ 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> 

2. Use servlet to process reports:

The main difference is that servlet directly outputs the report stream:

First, write a customdatasource class to implement the jrdatasource interface of the report, and convert the vector to the Data source:

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

Output HTML:

Servletcontext context = This. getservletconfig (). getservletcontext (); file reportfile = new file (context. getrealpath ("/reports/test. jasper "); // load the report path if (! Reportfile. exists () {response. setcontenttype (content_type); printwriter out = response. getwriter (); out. print ("<script language = 'javascript '>"); out. print ("alert ('No report found! '); "); Out. print ("</SCRIPT>"); return;} map parameters = new hashmap (); response. setcontenttype (content_type); printwriter out = response. getwriter (); try {jasperreport = (jasperreport) jrloader. loadobject (reportfile. getpath (); // load the report/* Java. lang. reflect. field pageheight = jrbasereport. class. getdeclaredfield ("pageheight"); pageheight. setaccessible (true); pageheight. setint (jasperreport, 500 ); */Jasperprint = jasperfillmanager. fillreport (jasperreport, parameters, new customdatasource (vector) Re. get (1); // load the data source and parameters. The data source here uses jrdatasource, so implement jrdatasource interface 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! = 'Textea ') {event. keycode = 0 };}\ N "; header + =" document. oncontextmenu = function () {return false ;}; \ n "; header + =" </SCRIPT> \ n "; header + =" <HTML> \ n "; header + = "
PDF output:
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 output:
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>");}
Related Article

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.