Jasper Export PDFs and xls__jsp in JSPs

Source: Internet
Author: User
Tags documentation export class flush getmessage xml parser

Environment configuration

1 Installing the Java JDK correctly

2 Put ireport in the C:/ireport.

3 Put Ant in C:/ant (I'm using Bea's ant path is d:/bea/weblogic81/server/ant)

4 put Jasperreports-1.2.0.jar into the current classpath (no Plus, I'm using ireport/lib already exists)

5 Place Itext-1.3.1.jar into C:/ireport/lib (no plus, I'm using ireport/lib already exists)

6 Modify Ireport/ireport.bat file, add the following content

Set java_home=c:/j2sdk1.4.2

Set ant_home=d:/bea/weblogic81/server/

Set Ireport_home=c:/ireport rem%ant_home%/bin/ant javadocs%ant_home%/bin/ant IREPORT

What I have modified is:

Set java_home=c:/j2sdk1.4.2

Set ant_home=d:/bea/weblogic81/server/

Set ireport_home=f:/backup/ireport-1.2.0 rem%ant_home%/bin/ant javadocs%ant_home%/bin/ant IREPORT

(But for the above changes, the feeling is not useful)

7 provide a database of normal service delivery

Now the high version of the ireport is not required to be configured and can be used directly.

Learn about the packages used to make reports

1 Jasperreports-1.0.1.jar jasperreports is the core content of ireport, Jsperreport is a report making program that uses its rules to develop an XML file and then compiles a. jsper file, this. jsper file is what we really use, it's very much like a. jsp file, using its compiled servlet. (http://jasperreports.sourceforge.net/)

The 2 Itext-1.3.1.jar itext is an open source Java class Library that is used to generate PDF files. If you want to display Asian characters such as Chinese in the generated PDF file, you must also download the Itext Asian character Fu Bao Itextasian.jar (Http://itextdocs.lowagie.com/downloads/iTextAsian.jar)

3 Jfreechart-1.0.0-rc1.jar Jfreechart is a free, powerful statistical graph generation tool that can directly generate all kinds of png,jpg files. (http://www.jfree.org/jfreechart/)

The 4 Jcommon-1.0.0-rc1.jar Jcommon is a useful set of classes. It has been used in jfreechart,jfreereport and other projects. This class library includes the following functions: Text utilities, a user interface class to display information about the application, a Layout customization manager, a date selection panel, a serialization tool class, and an XML parser support class. (http://www.jfree.org/jcommon/)

5 Poi-2.0-final-20040126.jar Apache Jakata Project Poi subproject, the goal is to process ole2 objects. At present more mature is the HSSF interface, processing Ms Excel (97-2002) object. It's not like we're just using CSV to generate unformatted things that can be converted by Excel, but real Excel objects, you can control some properties like Sheet,cell and so on. The direct call to POI package is not ireport, but jasperreport. (http://www.apache.org/dyn/closer.cgi/jakarta/poi/)

Use introduction

1 Start: Click Ireport/ireport.bat start

2 Modify Locale: Language in Tools-option-general change-apply

3 Create report file-new document Enter name-ok portrait is portrait, landscape is horizontal.

4 Connection Data source Datasource-connection/datasource-new-connections porperties-input name-select JDBC Driver,jdbc url-input username and password , the-test test is saved by indicating that the data source connection is correct-save (note: The database drive must be guaranteed in the Lib directory)

5 Basic Domain Description

The title field is used to put the total caption of the report

Pageheaher field as the name suggests page header

The ColumnHeader field is used to put static text, which is the part that does not loop.

The detail field is used to place the text field, which is the loop part.

The PageFooter field is used to put the statistical parameters on this page.

The summary field is used to put the statistical parameters of the entire table.

You can adjust the length of each field directly, or you can adjust it by band properties (in my project, only the title and detail are set, the total title of the report and all parameters fields are displayed in title, and the list fields that need to be circulated are displayed in detail )

6 adding fields to the report static text Edit-insert element-static text mouse Drag add in the page double-click or right key properties in the static text Tab input field name, if the display has garbled, Font-font name in the "Chinese GB2312" border you can set table edge styles

7 adding fields to the report text field Edit-insert Element-text field Mouse Drag add double click in page or right key properties in the Text field, type the names of the fields as $f{text_field_ Name},

F is represented as a field variable and is extracted from the database, which you want to display in the report,

P is the parameter parameter, the application needs to provide the entrance to the report, for example, to provide a where statement when the report is interpreted as a condition value, you can use $p (parametername) such as: SELECT * from bugs where proname= $P { ProjectName} ORDER by Proname,modulename

V is a variable (display font color is green, indicates the format is correct) border can set table edge style

8 Adjust the report layout mouse drag each field, splicing the desired report layout, if the mouse clicks the field, the display is red, indicating that the field spans two fields appear as green, indicating that two fields are superimposed in blue, indicating that the field is positioned correctly

9 Report Add SQL query statement data source-> report query (datasource-report query) fills in SQL statements in reports SQL queries. If the statement is correct, a normal table field appears in the field below. (You can select fields to be used as field from all displayed fields, click OK and automatically add as field dynamic fields)

10 Add Dynamic field Preview to report-> report Field (View-fields) Create a new field, the field name must be added to the Fields in the report, and must be present in the SQL result set. (Drag the field in the fields directly onto the report.)

11 adding parameter previews for SQL statements-> report parameters (View-parameters) add a parameter to parameters Paratemeter name is the parameter name, written as "$P {parameter name}" in the SQL statement Paratemeter Select the parameter type in the class type. Note: If you are int, it is a good idea to change the class type of the field in the report field to java.lang.String type. Alternatively, regardless of what data type the field is originally, select the java.lang.String type directly in the Paratemeter class type, and then fill in the default value expression "integer.tostring (integer) ".

12 Add report variable preview-> report variable $V {variable name} (no use!)

13 Processing Font Select field-> right->properties->font (double-click also can) report font select Global Font (only for this report) font name Select the font to display in ireport PDF font name selection Choose the font displayed in the PDF rotation Select whether the content is rotated (very useful) PDF Encoding Chinese to use unigb-ucs2-h, external font to choose Identity-h

14 set the report's Global Font Preview-> report font (VIEW-FONT)

15 Compile Jrxml Build-> compile (build-compile) compile the binary file with a suffix named Jasper, which can be called directly to the program.

Web Project Application

1 JSP output PDF report

Packages that need to be put into the project Itext-1.3.1.jar Itextasian.jar Jasperreports-1.0.1.jar JSP

Example of exporting PDF

{

<%@ page import= "java.sql.*"%>
<%@ page import= "java.util.*"%>
<%@ page import= "java.io.*"%>
<%@ page import= "Net.sf.jasperreports.engine.JasperFillManager"%>
<%@ page import= "Net.sf.jasperreports.engine.JasperPrint"%>
<%@ page import= "Net.sf.jasperreports.engine.JRException"%>
<%@ page import= "Net.sf.jasperreports.engine.JasperRunManager"%>
<%
String rowid = "1";//Initialize variable
Connection conn= drivermanager.getconnection ("proxool.test");//Connect database from data source
Load Jasper File Application
File Exe_rpt = new file (Application.getrealpath ("/reports/test.jasper"));
rowID is the name of the ireport variable $p{rowid}
Map parameters = new HashMap ();
Parameters.put ("rowID", ROWID);
try{
Fill
Jasperprint jasperprint = Jasperfillmanager.fillreport (Exe_rpt.getpath (), parameters,conn);

Generate PDF
byte[] bytes = jasperrunmanager.runreporttopdf (Exe_rpt.getpath (), parameters,conn);

Response.setcontenttype ("Application/pdf");
Response.setcontentlength (bytes.length);
Servletoutputstream Ouputstream = Response.getoutputstream ();
Ouputstream.write (bytes,0,bytes.length);
Ouputstream.flush ();
Ouputstream.close ();
Conn.close ();
}catch (Jrexception ex) {
Out.print ("Jasper Output Error:" +ex.getmessage ());
}
%>


}

JSP output Excel Report

Packages that need to be put into the project Jasperreports-1.0.1.jar Poi-2.0-final-20040126.jar

Output Excel to note:

(1) Output Excel report must fields the boundary just fill full page, otherwise there will be a lot of blank appear.

(2) Delete records at the bottom of the empty line need to add parameters Exporter.setparameter (jrxlsexporterparameter.is_remove_empty_space_between_rows, Boolean.true);

(3) Remove redundant columnheader need to add parameter Exporter.setparameter (JRXLSEXPORTERPARAMETER.IS_ONE_PAGE_PER_SHEET,BOOLEAN.FALSE);

(4) In the ireport to fields plus border, the output of Excel will have a very black border, and Excel default Gray border will be very uncoordinated. But without border, the borders of each table are not displayed in Excel output.

The workaround is: The first step in the selected field-> right button->properties->common->transparent tick. The second step is to add the parameter Exporter.setparameter (jrxlsexporterparameter.is_white_page_background,boolean.false) to the output JSP page;

2 JSP Output Excel example

{

<%@ page import= "java.sql.*"%>
<%@ page import= "java.util.*"%>
<%@ page import= "java.io.*"%>
<%@ page import= "Net.sf.jasperreports.engine.JasperFillManager"%>
<%@ page import= "Net.sf.jasperreports.engine.JasperPrint"%>
<%@ page import= "Net.sf.jasperreports.engine.JRException"%>
<%@ page import= "Net.sf.jasperreports.engine.JRExporterParameter"%>//excel
<%@ page import= "Net.sf.jasperreports.engine.export.JRXlsExporterParameter"%>//excel
<%@ page import= "Net.sf.jasperreports.engine.export.JRXlsExporter"%>//excel
<%
String rowid = "1";
Connection conn= drivermanager.getconnection ("Proxool.test");

Load Jasper File Application
File Exe_rpt = new file (Application.getrealpath ("/excel/test_excel.jasper"));

rowID is the name of the ireport variable $p{rowid}
Map parameters = new HashMap ();
Parameters.put ("rowID", ROWID);

try{

Fill
Jasperprint jasperprint = Jasperfillmanager.fillreport (Exe_rpt.getpath (), parameters,conn);

Excel output
Bytearrayoutputstream ostream = new Bytearrayoutputstream ();

Jrxlsexporter exporter = new Jrxlsexporter ();

Exporter.setparameter (Jrexporterparameter.jasper_print, jasperprint);
Exporter.setparameter (Jrexporterparameter.output_stream, ostream);
Exporter.setparameter (jrxlsexporterparameter.is_remove_empty_space_between_rows,boolean.true); Delete the blank line at the bottom of the record
Exporter.setparameter (Jrxlsexporterparameter.is_one_page_per_sheet,boolean.false);//Remove redundant ColumnHeader
Exporter.setparameter (Jrxlsexporterparameter.is_white_page_background,boolean.false);//Display border
Exporter.exportreport ();

byte[] bytes = Ostream.tobytearray ();

if (bytes!= null && bytes.length > 0) {
Response.reset ();
Response.setcontenttype ("application/vnd.ms-excel");
Response.setcontentlength (bytes.length);
Servletoutputstream Ouputstream = Response.getoutputstream ();
Ouputstream.write (bytes,0,bytes.length);
Ouputstream.flush ();
Ouputstream.close ();

}else{
Out.print ("bytes were null!");
}
Conn.close ();
}catch (Jrexception ex) {
Out.print ("Jasper Output Error:" +ex.getmessage ());
}
%>

}

Summary ireport can display charts, pie charts, graphs, etc., can also show the compliance report

JasperReports Introduction:

Using JasperReports to generate reports is very simple, using only a few classes in the Net.sf.jasperreports.engine package to complete the report generation, preview, print, export and other functions.

1. Net.sf.jasperreports.engine.JasperCompileManager class.
Use several static methods of this class to complete the compilation of the report (see API documentation specifically)
There are two ways to Jaspercompilemanager when the compilation is complete:
1> returns a Jasperreport object
2> generates a. jasper file in the directory where the. jrxml file resides
Both of these methods are chosen by the programmer. However, I prefer to use the. jasper file, after all, the structure of the report is not changed every day, so it's not a good deal to recompile the report every time.

2. Net.sf.jasperreports.engine.JasperFillManager class
The function of this class is to populate the report with data. It can also be used with Jasperreport objects. Jasper file as a report template.
It also has 2 processing methods:
1> returns a Jsaperprint object.
2> generates a. jrprint file in the directory where the. jasper file resides
This class uses the implementation of the Net.sf.jasperreports.engine.JRDataSource interface as the data source. Any class that implements Jrdatasource can be used as a data source
Some data sources are defined in the Net.sf.jasperreports.engine.data package and can be selected according to your own needs. Here I'm using Jrtablemodeldatasource as
The data source (because my report is also displayed in the table).

3. Net.sf.jasperreports.engine.JasperPrintManager and Net.sf.jasperreports.engine.JasperExportManager
The role of the two classes is to print, export reports
They use Jasperprint and. jrprint files as input.
You can use the inside method according to your own needs.

Cases:
Import net.sf.jasperreports.engine.*;
Import net.sf.jasperreports.view.*;
public class Compilereport {
public static void Main (String args[]) {
try {
Compiling report.jrxml and generating report.jasper files in the directory where report.jrxml resides
Jaspercompilemanager.compilereporttofile ("Report.jrxml");
Fill in the data, here is the Jremptydatasource
Jasperfillmanager.fillreporttofile ("Report.jasper", NULL, New Jremptydatasource (50));
Preview the report, false to represent not using an XML file.
Jasperviewer view = new Jasperviewer ("Reports.jrprint", false);
View.pack ();
View.setvisible (TRUE);
}
catch (Exception e) {
E.printstacktrace ()
}
}
}


Http://www.heci.net message Network. ]
JasperReports Learning Notes

Version: jasperreports-0.6.7
Study Data Source: http://jasperreports.sourceforge.net

I. Demand (REQUIREMENTS)
JasperReports tools and classes to use
1. JDK (Java Development environment)
JDK 1.2.2 or higher
2. XML
JAXP 1.1 XML Parser (XML parser)

Jakarta Commons digester Component (version 1.1 or later)
http://jakarta.apache.org/commons/digester/

Jakarta Commons beanutils Component (version 1.1 or later)
http://jakarta.apache.org/commons/beanutils/

Jakarta Commons Collections Component (version 1.0 or later)
http://jakarta.apache.org/commons/collections/

Jakarta Commons Logging Component (version 1.0 or later)
http://jakarta.apache.org/commons/logging/
3. JDBC (Connection database)
JDBC 2.0 Driver

4. PDF (converted to PDF file for use)
Itext-free java-pdf Library by Bruno Lowagie and Paulo Soares
(version 1.01 or later)
http://www.lowagie.com/iText/

5. XLS (converted to Excel files)
Jakarta POI (version 2.0 or later)
http://jakarta.apache.org/poi/

Second, quick understanding (quick to)
1. Main classes (primary class)
The main class used when using JasperReports
Net.sf.jasperreports.engine.JasperCompileManager
Net.sf.jasperreports.engine.JasperFillManager
Net.sf.jasperreports.engine.JasperPrintManager
Net.sf.jasperreports.engine.JasperExportManager
These classes provide a number of static methods for compiling, populating, printing, and exporting reports. For more information, refer to the Javadoc documentation for JasperReports.

Net.sf.jasperreports.view.JasperViewer
This class is used to preview the generated report (generated reports.).

Net.sf.jasperreports.view.JasperDesignViewer
This class is used to preview the report design.

2. Compile report Design compiling a
The XML file defines the report design. Compile report designs (generate reports) to generate reports. Web http://jasperreports.sourceforge.net/ Quick.how.to.html introduces the static method of Net.sf.jasperreports.engine.JasperCompileManager class Compilereportxxx () to compile the report design. Design). However, Jaspercompilemanager is not in favor of compiling report designs using this method, and recommends using the Jaspercompilemanager method Compilereportxxx () instead.
When compiling a report design, JasperReports engine first examines the template, determines whether it is consistent, and then converts all report expressions (reports expressions), resulting in a. jasper file. To make the compilation work as flexible as possible, you can implement interface Net.sf.jasperreports.engine.design.JRCompiler.

3. Preview report Design Viewing a
Use the Net.sf.jasperreports.view.JasperDesignViewer program to preview. His main () method accepts either the report design file name (XML) or the compiled. Jasper file.

4. Fill in report Filling a
Compile the report design (XML file) to get the report file (. jasper), and then invoke the method Fillreportxxx () of the Net.sf.jasperreports.engine.JasperFillManager class to get the report ( Jasperprint).
5. Preview report Viewing a
Generated reports can be viewed using the Net.sf.jasperreports.view.JasperViewer application.
In its main () method, it receives the name of the file which contains the "" to view.
I did not test successfully.
6. Printing A
Generated reports can is printed using the PrintReport (), printPage () or Printpages () static methods exposed by the NET.SF . Jasperreports.engine.JasperPrintManager class.

7. Exporting to PDF, HTML, XLS, CSV or XML format
After you populate the report file (. jasper file) with the report (Jasperprint), you can use the methods of the Net.sf.jasperreports.engine.JasperExportManager class Exportreportxxx () Export to file Pdf,html,xml in various formats.
After have filled a, we can also export it in PDF, HTML or XML format using the Exportreportxxx () methods of the Net.sf.jasperreports.engine.JasperExportManager class.


Third, the jasperreports work flow:

According to the process of the above diagram, JasperReports to do the report a step:

1, report design, you can use ireport visual tools to achieve, generate XML files. When you are finished, you can directly compile the XML file directly to step 3.
2. If a report design file (XML file) already exists, you can load the report design with the Net.sf.jasperreports.engine.xml.JRXmlLoader.load () method, which returns the Jasperdesign object. You can modify report design by Jasperdesign objects, such as adding, removing fields, adding, deleting variables, adding, deleting groups, and so on.
3, after the completion of the report design, the next can be compiled newspaper design, The compiled report design can be implemented using the Compilereport () method of Class Net.sf.jasperreports.engine.JasperCompileManager, which can compile XML files or Jasperdesign objects to produce Jasperrepor T object, the Jasperreport object can be serialized and can be saved as a file (usually a. jasper file). Class Net.sf.jasperreports.engine.JasperCompileManager can also convert a report into a report design file (an XML file). After you get the Jasperreport object (which can instantiate a Jasperreport object from the. jasper file), populate the report with the data generation Jasperprint object. The Jasperprint object can be serialized and saved as a file. With Jasperprint objects, you can print, browse, and convert files to other formats, such as Pdf,html,xml,xls,csv and so on, which are the final results we want. Although the Jasperprintmanager class can be exported as a Pdf,xml file, but is not supported for export using the Jasperprintmanager class, it is recommended that you export the Pdf,html,xml file with the Jasperexportmanager class ; To export XLS and CSV files, Use professional export class Net.sf.jasperreports.engine.export.JRXlsExporter class and Net.sf.jasperreports.engine.export.JRCsvExporter class
Code snippet exported to XLS:
Jrxlsexporter exporter = new Jrxlsexporter ();//Create Instance
Design parameters
Exporter.setparameter (Jrexporterparameter.jasper_print, jasperprint);
Exporter.setparameter (Jrexporterparameter.output_file_name, strDestFile);
Exporter.setparameter (Jrxlsexporterparameter.is_one_page_per_sheet, Boolean.false);
Exporter.exportreport ()//Export

Exporting to CSV files is similar to XLS.

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.