Java Utility case file export (Jasperreport pit record)

Source: Internet
Author: User
Tags export class getmessage throwable

write on the front

Want to come to the new company also nearly five months, trance for a moment.

Turned over the blog, because too busy, but also for nearly five months did not seriously summed up.

Just taking advantage of today's wife out of the group to build the opportunity to record the recent period of time encountered in the Tai Hang-jasperreport.

in June, I wrote a small demo that uses a POI file to import and export, Java Utility case file import and export (POI mode).

Although simple, but the principle of enterprise application is basically that, but the package is better, not as I wrote before each cell needs to be defined, in fact, the way poi is one of my most respected way now. The main reason is that JXL does not support the Xlsx,jasperreport pit is too big, eh. Below to get to the point, to introduce today's pig's foot jasperreport or call it ireport or jasperstudio, of course, the following two is its visual tools.

What's a jasperreport?

This goods in fact in the domestic user also many, is a foreign product, and can be said in the Java Report Field application is quite extensive.

I had just contacted this report when it is still quite like, the main thing is its visual tools, really let me stop, unexpectedly can be a simple way to design Java report. Speaking of drawing is a visual tool that allows us to visualize the design of a report template, and it supports output in a wide range of file formats, including Excel, WORD, PDF, HTML, XML, CSV, and more.

It seems to be not very powerful, one design, multiple reuse. Of course, powerful things, often have two sides, this is not I met, tortured me for quite a long time, the text will be described in detail.

Jasperreport's big breasted brother

I said before, jasperreport or call it ireport or jasperstudio, in fact, this is not accurate. Two younger brother ireport, three younger brother Jasperstudio is actually jasper the Assistant Visual design tool, you do not have it also can design Jasper report, write little XML white. 5.5 Before this tool was called ireport,5.5 with the birth of three younger brother Jasperstudio, ireport was completely replaced, in fact, the two tools are basically the same, a milk compatriots.

Specific work Flow:

① First Jasper Gets the XML file that needs to output the format information, and then compiles the. Jasper type of file from the XML file, and the Jasper file can be loaded in our application to generate the final report. There is no familiar feeling, yes, this is similar to Java, need to compile a bit.

, is ireport operation interface, jasperstudio similar, do not post, we can own Baidu under.

a brief introduction to each type of band.
(1)title band: Title section is displayed only on the top part of the first page of the entire report, except for the first page, no matter how many pages in the report will not appear in the title band content.

(2)PageHeader Band: As the name implies, the contents of the PageHeader paragraph will be in each page of the entire reportAppears in the upper part of the page, and if it is the first page of the report, the contents of the PageHeader are displayed in theunder Title Band, the contents of PageHeader in all pages except the first page will be displayed at the top of the page.

(3)pagefooter Band: Displayed at the bottom of the page.

(4)lastpagefooter Band: Displayed at the bottom of the last page.

(5)Detail Band: report Content section, in this Band design report needs repeating content, Detail segmentwill appear on every page of the content.

(6)ColumnHeader Band: For the detail Band of the header segment, generally in this paragraph to draw the table of the reporthead.

(7)Columnfooter Band: The footer segment for detail Band.

(8)Summary Band: The total section of the table, which appears after detail Band on the last page of the entire report, is generally used to count the aggregate values of one or more fields in the report.

Above is the visual tools of all, in fact, how to use very simple, start groping under will, since it is a record of the pit, this nature is not the focus, do not say.

application in the code

This is my summary of the steps that may be described is not very accurate, everybody make up

① design template, generate Jrxml file, ↑↑ the above visualization tool to design the template style you need

② compiled templates, Jrxml compiled into Jasper files, just like the. Java and. class files in Java, the need to run a program is a binary file of *.jasper.

In fact, this step can be generated directly with ireport compilation. Jasper, of course, can also be compiled at run time through the Jasper program. However, it is recommended that the Jasper version is the best version of ireport or Jasperstudio if compiled in the program.

③ Execution Report (data populate to report)

1. Load template to generate Jasperreport object

2, use Jasperfillmanager, generate Jasperprint Object

④ finally uses the Jrxlsxexporter export class to export or display the report

Loading Templates

Now that we have created the. Jasper or. jrxml file with the visualizer, it is natural that the program needs to be loaded.

Loaded code that 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 NewBaseexception ("Load Jasper Error", E); } Catch(jrexception e) {Throw NewBaseexception ("The Jrxml template transform to Jasper file error", E); } Catch(Throwable e) {log.error (e); Throw Newbaseexception (E.getmessage ()); }        } Else if(Urlpath.endswith (". Jasper")) {            Try{InputStream is=Url.openstream (); Jasperreport=(Jasperreport) jrloader.loadobject (IS); } Catch(IOException e) {Throw NewBaseexception ("Load Jasper Error", E); } Catch(jrexception e) {Throw NewBaseexception ("The Jrxml template file Error", E); } Catch(Throwable e) {log.error (e); Throw Newbaseexception (E.getmessage ()); }        } Else {            Throw NewBaseexception ("Invalid file!"); }
get a data source in a report

Here I use the JavaBean way to get

NULL ;             if null && fieldvalues.size () > 0) {                new  Jrbeancollectiondatasource ( fieldvalues);             Else {                new  jremptydatasource ();            }
Fieldvalues gets the Pojo collection for the database.
perform a report fill

Get Jasperprint Object

New Hashmap<string, object>= Jasperfillmanager.fillreport (Jasperreport, ParameterValue, DataSource);
Finally, we use Jrxlsxexporter to export the report

This is also the one place that requires the most configuration parameters

Newnew  jrxlsxexporter (); Exporter.setparameter (Jrexporterparameter.jasper_print, Jasperprint); Exporter.setparameter (Jrexporterparameter.output_stream, BAOs);
Exporter.exportreport ();

Complete, the data has been written to the output stream, how to output its own decision, is not much more than the other way of code introduction.

It is true that Jasperreport has incomparable advantages in code writing, and various APIs have been packaged well. But maybe it's just doing too much, and there are a lot of problems.

Jasperreport's Problem1, two lines before the blank

If you use the above code to export Excel, you will find that the background of Excel is white, there is no Excel a small lattice, this is because the Jasper default background is white, so in the export of other formats are good compatibility, of course, when we export Excel does not need. Just add the following two lines to resolve.

            // Remove the white space  before two lines             Exporter.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, the volume of data is very large, title multiple write

If you have a lot of sheet data, you may encounter a case where the header is printed multiple times, in which case you need to add a height setting.

Field PageHeight = Jrbasereport. class . Getdeclaredfield (                    "PageHeight");            Pageheight.setaccessible (true);            Pageheight.setint (Jasperreport, integer.max_value);
3. Problems with the type of cell

Sometimes we export Excel report, need to use Excel function calculation, if all is Text format, natural calculation, in this case, we need to use

// Automatic selection format exporter.setparameter (Jrxlsexporterparameter.is_detect_cell_type, boolean.true);

Remember that the field field selects the correct type at report design time.

4, multi-sheet problems

I above that simple example, just a file contains a sheet page, if our demand is a file export multiple sheet How to do, don't worry, this japser already thought for us.

Just change the export step above to the following

Newnew  jrxlsxexporter (); Exporter.setparameter (Jrexporterparameter.jasper_print_list, Listjasperprint); Exporter.setparameter (Jrexporterparameter.output_stream, BAOs); // set to True to put each individual Jasper object into a sheet page in one Excel Exporter.setparameter (jrxlsexporterparameter.is_one_page_per_sheet,boolean.true);
Jrexporterparameter.jasper_print_list, passing in a collection of Listjasperprint, each jasperprint a sheet page.
5, Linux start without error, but unable to export the report

In fact, this problem also bothered me for a long time, and later in the help of the big guy just think of the problem, because it throws is not a exception, but error. I saw some classmates on the Internet asking this question, so I posted it.

Can be captured with throwable, you can get error message: Java.lang.InternalError:Can ' t connect to X11 Window server using ': 0.0 ' as

Workaround: Modify tomcat/bin/catalina.sh plus java_opts= "$JAVA _opts-djava.awt.headless=true"

6, Big Data memory overflow and memory leak problem!!

Here's what we need to say. EXCEL 03 and 07 version of the difference, 03 version I remember as if it is only support 65532 lines, and the 07 version after the larger, the specific number I forgot, anyway, not an order of magnitude.

Jrxlsxexporter supports exporting xlsx files,
Jrxlsexporter is an XLS file that is well recognizable, and the exported tool is the same as the Excel format.

Then there is memory overflow and memory leak issues, which I believe are basically met by friends who play Java.

The most common solution to memory overflow is to increase the memory of the container, increase the size of Tomcat memory, the method can be Baidu, there are many, do not repeat the wheel.

Here's a reminder that if you're using Tomcat, the Windows Installer, the unzip version, and the Linux version are all configured differently, and you need to be careful.

Here I need to introduce is the way of jasperreport, in fact, Jasperreport is the big data has a solution, in very early version of the launch, Jrfilevirtualizer emulator.

What is the use of this thing, in fact, it will be based on the parameters you set, the data will be written to the temporary file on the hard disk, so as to solve the problem of populating the report when the memory consumption is too large overflow.

Currently, Jasperreport has 3 emulators, all of which are used to solve this problem.

respectively:

①jrfilevirtualizer

②jrswapfilevirtualizer

③jrgzipvirtualizer

What's the difference between these three emulators?

First is the introduction of the earliest Jrfilevirtualizer, when I test, when the export of about 30W of data, will be reported memory overflow, and later added to the normal export. This emulator will generate a temporary file for each object on the hard disk to solve the memory consumption problem, but because the resulting temporary files are more, virtually increase the file creation and deletion of memory, so it is not recommended.

// Write multiple Files New Jrfilevirtualizer (2, Catchpath); MapNew hashmap<string, object>(); Parametervalue.put (Jrparameter.report_virtualizer, Virtualizer);
Virtualizer.setreadonly (TRUE);
Catchpath file cache path, must be real, otherwise it will be an error.

Then there was Jrswapfilevirtualizer, which was introduced to solve the jrfilevirtualizer problem. This emulator, will only create a temporary file, each object will be part of this file, so the reduction of file creation and deletion of memory consumption, in fact, this is not particularly recommended.

// Write a single file New Jrswapfile (Catchpath, 4096,newtrue);        Map New Hashmap<string, object>();p arametervalue.put (Jrparameter.report_virtualizer, Virtualizer);
Virtualizer.setreadonly (TRUE);

Finally Jrgzipvirtualizer this, see gzip, don't know if you have a link to compress this word. Yes, the emulator uses a special compression algorithm that compresses the memory footprint to One-twentieth or one-tenth, which is amazing.

New Jrgzipvirtualizer (2); MapNew hashmap<string, object>= Jasperfillmanager.fillreport (Jasperreport, ParameterValue, DataSource);

Said so much, in short, is three kinds of emulator to solve memory overflow problem, I also read a lot of blog inside write use Jrfilevirtualizer, solve memory big data problem. And then I'm here to say, I most most do not recommend the use of the Jrfilevirtualizer emulator, because it not only creates a large file consumption, there is a serious bug, memory leaks!!! and Jrswapfilevirtualizer also have this problem.

In addition, it is necessary to note that the emulator is not used, there will be a memory leak problem, when you export the report, dump the stack information, Will find Net.sf.jasperreports.engine.fill.JRTemplatePrintText class instances are particularly many, can not be recycled, can not be recycled!!! And the latest version of Japserreport 6.x still has this problem, there are many such problems in Jasper community and stack overflow, and there is no solution.

Jrgzipvirtualizer Simulator is recommended here, although there is still a leak problem, but because of the unique compression algorithm, the memory leak problem has been controlled in a very small range, is a mitigation of the scheme, probably leaked memory consumption eased by more than 90%.

In general, I have now given up this kind of plan, write out also for later brother less detours. Took a POI tool class, and then ready to change all the reports to POI export way, saying that the big data of poi is very good.

Development on the road pit, not written too good also please forgive me. Reprint also please indicate the source: small sell shop of grandfather Http://www.cnblogs.com/laoyeye/p/7707149.html .

Java Utility case file export (Jasperreport pit record)

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.