JasperReport for java learning, javajasperreport

Source: Internet
Author: User
Tags export class

JasperReport for java learning, javajasperreport

Next we will go to the topic to introduce today's pig JasperReport, ireport, or jasperstudio. Of course, the next two are their visualization tools.

What is JasperReport?

In fact, this product has many users in China and is a foreign product. It can be said that it is widely used in the JAVA Report field.

When I first came into contact with this report, I still liked it very much. The most important thing was its visualization tool, which really gave me the desire to stop. I could design a JAVA report by drawing a simple graph. Drawing is a visual tool that allows us to visually design a report template, and it supports a wide range of output file formats, including EXCEL, WORD, PDF, HTML, XML, CSV, etc.

It seems that it is not very powerful, one-time design, multiple reuse. Of course, the powerful things often have two sides. I will not be able to meet them, but I am suffering for a long time. I will describe them in detail later.

JasperReport's big brother

As I mentioned earlier, JasperReport, or jasport or jasperstudio, is inaccurate. Port and jasperstudio are actually auxiliary visual design tools of jasper. You can design jasper reports without using them and write more XML white data. Before June 5.5, this tool was called ireport. After June 5.5, with the birth of the third brother jasperstudio, ireport was completely replaced. In fact, these two tools are basically the same.

Specific workflow:

① First, Jasper will obtain the xml file of the format information to be output, and then compile and translate it from the xml file. the jasper file can be loaded in our application to generate the final report. Are there any familiar feelings? Yes, this is very similar to java and needs to be compiled.

That is, the ireport operation interface. If jasperstudio is similar, you will not post it. You can click here on your own.

A brief introduction to each type of band.

(1) Title band: The title segment is only displayed on the top of the first page of the entire report, except for the first page, no matter how many pages are in the report, the content in the Title band will no longer appear.

(2) pageHeader Band: as the name suggests, the content in the pageHeader segment will appear on every page of the entire report and be displayed on the top of the page. If it is the first page of the report, the content in pageHeader is displayed under Title Band, and the content in pageHeader in all pages except the first page is displayed at the top of the page.

(3) pageFooter Band: display at the bottom of the page.

(4) lastPageFooter Band: display at the bottom of the last page.

(5) Detail Band: The content segment of the report, which must be repeated in the Design Report. The content of the Detail segment appears on each page.

(6) columnHeader Band: For the header segment of the Detail Band, the report header is usually drawn in this segment.

(7) columnFooter Band: end segment of the Detail Band table.

(8) Summary Band: The total segment of the table, which appears after the Detail band on the last page of the entire report. It is generally used to count the total value of one or more fields in the report.

The above is the full list of visualization tools. In fact, how to use it is very simple. It will be easy to get started. Since it is a pitfall recording, this is naturally not the focus, not to mention it.

Application in code

This is my summary. It may not be very accurate.

① Design the template, generate the JRXML file, and design the template style you need using the visualization tool above.

② Compile the template. JRXML is compiled into the Jasper file. Just like the. java and. class files in java, the binary file *. jasper is required to be run in the program.

In fact, this step can be directly compiled using ireport to generate. jasper. Of course, it can also be compiled through the jasper program at runtime. However, it is recommended that the jasper version be the same as the ireport or jasperstudio version if it is compiled in the program.

③ Execute the report (data is filled into the report)

1. Load the template to generate the Jasperreport object

2. Use JasperFillManager to generate the JasperPrint object

④ Use the JRXlsxExporter export class to export or display reports

Load Template

Since we have used a visualization tool to generate a. jasper or. jrxml file, we naturally need to let the program load it.

The loaded code returns the jasperport object.

    if (urlPath.endsWith(".jrxml")) {      //compile jrxml to jasper      try {        InputStream is = url.openStream();        jasperReport = JasperCompileManager.compileReport(is);      } catch (IOException e) {        throw new BaseException("Load jasper error", e);      } catch (JRException e) {        throw new BaseException("The jrxml template transform to jasper file error", e);      } catch (Throwable e) {        log.error(e);        throw new BaseException(e.getMessage());      }    } else if (urlPath.endsWith(".jasper")) {      try {        InputStream is = url.openStream();        jasperReport = (JasperReport) JRLoader.loadObject(is);      } catch (IOException e) {        throw new BaseException("Load jasper error", e);      } catch (JRException e) {        throw new BaseException("The jrxml template file error", e);      } catch (Throwable e) {        log.error(e);        throw new BaseException(e.getMessage());      }    } else {      throw new BaseException("Invalid file!");    }

Obtain data sources in a report

Here I use the javabean method to obtain

      JRDataSource dataSource = null;      if (fieldValues != null && fieldValues.size() > 0) {        dataSource = new JRBeanCollectionDataSource(fieldValues);      } else {        dataSource = new JREmptyDataSource();      }

FieldValues is the pojo set obtained from the database.

Execute report Filling

Obtain the jasperprint object.

Map<String, Object> parameterValue = new HashMap<String, Object>();jasperPrint = JasperFillManager.fillReport(jasperReport, parameterValue, dataSource);

Finally, we use JRXlsxExporter to export the report.

This is also the place where the most parameters need to be configured

baos = new ByteArrayOutputStream();exporter = new JRXlsxExporter();exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, baos);
exporter.exportReport();

The data has been written into the output stream. How to output the data is determined by yourself? It is much more informative than other code methods.

In code writing, JasperReport has incomparable advantages, and various APIs have been encapsulated. However, there may be too many problems.

JasperReport Problems

1. Blank before two rows

If you use the above Code to export an EXCEL file, you will find that the background of the Excel file is white and there are no small cells in the Excel file. This is because the jasper background is white by default, in this way, compatibility can be achieved when exporting other formats. Of course, it is not required when exporting EXCEL. You only need to add the following two lines to solve the problem.

// Remove the blank exporter before the two rows. setParameter (JRXlsExporterParameter. IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, Boolean. TRUE); exporter. setParameter (JRXlsExporterParameter. IS_REMOVE_EMPTY_SPACE_BETWEEN_COLUMNS, Boolean. TRUE); // set the background color of the Excel table to the default white exporter. setParameter (JRXlsExporterParameter. IS_WHITE_PAGE_BACKGROUND, Boolean. FALSE );

2. Large data volume, multiple title writes

If you have a large amount of data in a Sheet, you may encounter a situation where the header is printed multiple times. In this case, you need to add the height settings.

Field pageHeight = JRBaseReport.class.getDeclaredField(          "pageHeight");      pageHeight.setAccessible(true);      pageHeight.setInt(jasperReport, Integer.MAX_VALUE);

3. Cell type problems

Sometimes the Excel report we export requires Excel function computing. If all the data is in the text format, it cannot be calculated. In this case, we need to use

// Automatically select the format exporter. setParameter (JRXlsExporterParameter. IS_DETECT_CELL_TYPE, Boolean. TRUE );

Remember to select the correct type for the Field during report design.

4. Multiple Sheet problems

In my simple example above, a file contains a Sheet page. If we want to export multiple sheets from one file, don't worry. This Japanese SER has long been thought of for us.

You only need to replace the above export steps with the following:

Baos = new ByteArrayOutputStream (); exporter = new JRXlsxExporter (); exporter. setParameter (JRExporterParameter. JASPER_PRINT_LIST, listJasperPrint); exporter. setParameter (JRExporterParameter. OUTPUT_STREAM, baos); // if it is set to true, each separate jasper object in an excel file can be put into an exporter on a sheet page. setParameter (JRXlsExporterParameter. IS_ONE_PAGE_PER_SHEET, Boolean. TRUE );

JRExporterParameter. JASPER_PRINT_LIST: input a set of listJasperPrint. Each JasperPrint is a Sheet page.

5. No error is reported during Linux Startup, but the report cannot be exported.

In fact, this problem has also plagued me for a long time. Later I remembered the problem with the help of daxie, because it throws an Error instead of an Exception. I saw some people asking this question online, so I posted it.

You Can use throwable to capture and get the error message: java. lang. InternalError: Can't connect to X11 window server using ': 100'

Solution: Modify tomcat/bin/catalina. sh and JAVA_OPTS = "$ JAVA_OPTS-Djava. awt. headless = true"

6. Big data memory overflow and Memory leakage !!

Here we need to talk about the difference between EXCEL 03 and 07. I remember that version 03 only supports 65532 rows, but it will be much larger after version 07, I forgot the specific number. It is not an order of magnitude.

JRXlsxExporter supports exporting xlsx files,

JRXlsExporter is an xls file that is well recognized and exported in the same format as excel.

Then there is the problem of memory overflow and Memory leakage. I believe that many of my friends who are playing JAVA have encountered this problem.

The most common solution to memory overflow is to increase the container memory and increase the tomcat memory size. You can use Baidu to increase the memory size.

Note that if you are using tomcat, the configuration methods for windows installation, decompression, and Linux are different.

Here I need to introduce the JasperReport method. In fact, JasperReport has a solution for big data. In earlier versions, it was launched as a jrfile1_alizer simulator.

In fact, it will write data to a temporary file on the hard disk based on the parameters you set. This solves the problem of memory overflow during report filling.

Currently, JasperReport has three simulators to solve this problem.

They are:

① JRFileVirtualizer

② JRSwapFileVirtualizer

③ JRGzipVirtualizer

What are the differences between these three simulators?

The first is to launch the earliest jrfilealizer. during the test, when I export about data, the memory overflow will be reported. After this is added, the data can be exported normally. This simulator will store a temporary file generated by each object on the hard disk to solve the memory usage problem. However, because there are many temporary files generated, the memory consumption for file creation and deletion is virtually increased, therefore, it is not recommended.

// Write multiple files. JRFileVirtualizer extends alizer = new JRFileVirtualizer (2, catchPath); Map <String, Object> parameterValue = new HashMap <String, Object> (); parameterValue. put (JRParameter. REPORT_VIRTUALIZER, virtualizer );
Virtualizer. setReadOnly (true );

CatchPath is the File Cache path and must exist. Otherwise, an error is returned.

Then there is JRSwapFileVirtualizer, which was launched to solve the problem of JRFileVirtualizer. This simulator creates only one temporary file, and each object occupies part of this file. Therefore, it reduces the memory consumption for file creation and deletion. In fact, this is not particularly recommended.

// Write a single file RSwapFile arquivoSwap = new JRSwapFile (catchPath, 4096, 25); implements alizer = new JRSwapFileVirtualizer (2, arquivoSwap, true); Map <String, object> parameterValue = new HashMap <String, Object> (); parameterValue. put (JRParameter. REPORT_VIRTUALIZER, virtualizer );
Virtualizer. setReadOnly (true );

The last is JRGzipVirtualizer. If you see Gzip, you don't know if you are related to the word compression. Yes, this simulator uses a special compression algorithm to compress memory usage to 1/20 or. In short, it is amazing.

JRAbstractLRUVirtualizer virtualizer = new JRGzipVirtualizer(2);Map<String, Object> parameterValue = new HashMap<String, Object>();parameterValue.put(JRParameter.REPORT_VIRTUALIZER, virtualizer);jasperPrint = JasperFillManager.fillReport(jasperReport, parameterValue, dataSource);

After talking about this, there are three simulators to solve the memory overflow problem. I also read many blogs that use jrfilereceivalizer to solve the memory big data problem. Then I would like to say here that I do not recommend using the JRFileVirtualizer simulator most, because it not only consumes a lot of file creation, but also has a very serious BUG and Memory leakage !!! This problem also exists in JRSwapFileVirtualizer.

In addition, it should be noted that there will also be memory leaks without using the simulator. When you export the report, dump the stack information and you will find the net. sf. jasperreports. engine. fill. JRTemplatePrintText has many instances and cannot be recycled !!! This problem still exists in the latest version of japserreport 6.x. Many of these problems exist in the jasper community and Stack Overflow, but there is no solution.

The JRGzipVirtualizer simulator is recommended here. Although there is still a leakage problem, the memory leakage problem has been controlled in a very small range due to the unique compression algorithm. It is a solution to ease it, the leaked memory usage is reduced by more.

In general, I have now abandoned this solution, and I wrote it to avoid detours for later siblings. I used a POI tool class. Next I want to change all the reports to the POI export method. It is quite good to say that the POI big data solution is quite good.

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.