Jasper exports PDF and XLS in JSP

Source: Internet
Author: User
Tags export class xml parser

Environment Configuration

1. Correctly install and configure the Java JDK

2 put ireport in C:/ireport

3. Put ant in C:/ant (the ant path of Bea is D:/BEA/weblogic81/Server/ant)

4 place the jasperreports-1.2.0.jar in the current classpath (not added, I used ireport/lib already exists)

5 place the itext-1.3.1.jar to C:/ireport/lib (not added, I used ireport/lib already exists)

6. Modify the ireport/ireport. BAT file and 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

I modified the following:

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

(However, it seems useless to make the above changes)

7. Provide a database for normal service provision

You can directly use the ireport of a later version without configuring it.

Understand the packages used to create reports

1 jasperreports-1.0.1.jar jasperreports is the core content of ireport, jsperreport is a report Making Program, use its rules to create an XML file, and then compile and generate. jsper file. the jsper file is actually used. JSP file, which uses the compiled servlet. (http://jasperreports.sourceforge.net /)

2 itext-1.3.1.jar itext is an open source Java class library that is used to generate PDF files. To display Chinese and other Asian characters in the generated PDF file, you must also download the 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, can directly generate PNG, JPG and other types of files. Http://www.jfree.org/jfreechart)

4 jcommon-1.0.0-rc1.jar jcommon is a set of useful classes. it has been used in jfreechart, jfreereport, and other projects. this class library contains the following functions: Text utilities, a user interface class used to display information about applications, layout customization manager, a date Selection Panel, serialization tool class, XML Parser Support class. http://www.jfree.org/jcommon)

5 poi-2.0-final-20040126.jar Apache's jakata project's poi sub-project with the goal of processing ole2 objects. Currently, the hssf interface is mature for processing MS Excel (97-2002) objects. It is not just a CSV file that can be converted from Excel, but a real EXCEL object. You can control attributes such as sheet and cell. The direct call to poi package is not ireport, but jasperreport. Http://www.apache.org/dyn/closer.cgi/jakarta/poi)

Introduction

1. Start: Click ireport/ireport. BAT to start

2. Modify the language environment: change in language in tools-Option-General-apply

3. Create a report file-new document enter the name-OK portrait is vertical, and landscape is landscape.

4. Connect to the data source datasource-connection/datasource-New-connections porperties-enter a name-select JDBC driver, jdbc url-enter username and password, -test indicates that the data source connection is correct.-Save and save (note: the database driver must be in the lib directory)

5 basic domain description

The title field is used to place the title of a report.

Pageheaher domain name as the name suggests page header

The columnheader field is used to put static text, that is, the non-circular part.

The detail field is used to put the text field, that is, the circular part.

The pagefooter field is used to store the statistical parameters on this page.

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

You can directly adjust the length of each domain, or adjust it through band properties (in my project, only the title and detail are set, display the report title and all parameters fields in the title, and display the list fields that need to be recycled in the detail)

6. Add the field static text edit-insert element-static text to the report by dragging the mouse. Double-click the field on the page or right-click Properties and enter the field name in the static text tab. If garbled characters are displayed, select "Chinese gb2312" from font-font name to set the table edge style.

7. Add the text field edit-insert element-text field to the report by dragging the mouse. Double-click the field on the page or right-click Properties and enter the field name in text field, the style is like $ f {text_field_name },

F indicates the field variable, which is extracted from the database and the database content you want to display in the report,

P is the parameter, which is the entry that the application must provide to the report. For example, if you want to provide the where statement condition value when the report is interpreted, you can use $ P (parametername) for example: select * from Bugs where proname = $ P {projectname} order by proname, modulename

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

8. Adjust the report layout move the mouse over each field to splice the expected report layout. If you click the field and the field is displayed in red, the field is displayed in green across two fields, the two fields are displayed in blue, indicating that the field is in the correct position.

9. Add an SQL query statement to a report. Choose data source> REPORT query (datasource-REPORT query) and enter an SQL statement in Report SQL query. If the statement is correct, a normal table field is displayed in the field below. (You can select the field to be used as the field from all the fields displayed, click OK, and then automatically add it as the field dynamic field)

10 Add a dynamic field preview to the report-> View-fields to create a new field. The field name must be the same as the name added to fields in the report, it must also exist in the SQL result set. (drag fields in fields to the report)

11 add parameter preview for SQL statements-> View-parameters to add a parameter paratemeter name in parameters, which is the parameter name, select the parameter type in "$ P {parameter name}" paratemeter class type in the SQL statement. Note: For int type data, it is best to change the class type of this field to Java. Lang. string type in the Report field. Another method is to directly select Java in paratemeter class type regardless of the Data Type of the field. lang. string type, and enter "integer. tostring (integer )".

12 Add Report variable preview-> report variable $ V {variable name} (not used !)

13. process the selected Font Field. Right-click the field and choose Properties> font (double-click the Field). Report Font: select the global font (only for this report) font Name select the font displayed in ireport PDF Font Name select the font displayed in the PDF rotation select whether the content is rotated (useful options) PDF encoding Chinese to use UniGB-UCS2-H, select Identity-h for the external font.

14. Set the global font preview for the report-> report font)

15 compile jrxml build-> compile (build-compile) to generate a binary file with the suffix Jasper, which can be called directly by the program.

WEB Project Application

1. jsp output PDF report

The package itext-1.3.1.jar itextasian. Jar jasperreports-1.0.1.jar JSP that needs to be put into the project

Example of output 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 the variable
Connection conn = drivermanager. getconnection ("proxool. test"); // connect to the database from the data source
// Load the 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 = 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

Package jasperreports-1.0.1.jar poi-2.0-final-20040126.jar to be put into the project

Note the following when outputting an Excel file:

(1) The fields boundary of the output Excel report must be filled with the entire page. Otherwise, a large number of blank spaces will appear.

(2) The parameter exporter. setparameter (jrxlsexporterparameter. is_remove_empty_space_between_rows, Boolean. True) must be added to the bottom of the delete record );

(3) The exporter. setparameter (jrxlsexporterparameter. is_one_page_per_sheet, Boolean. False) parameter must be added to delete redundant columnheaders );

(4) Add border to fields in ireport, then the output Excel file will have a very black border, which is not consistent with the default gray border of Excel. However, if border is not added, the border of each table is not displayed in the output Excel file.

Solution: in step 1, right-click the selected field and choose Properties> common> transparent. Step 2 Add the parameter exporter. setparameter (jrxlsexporterparameter. is_white_page_background, Boolean. False) to the output JSP page );

2 example of JSP Excel output

 

{

<% @ 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 the 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 = 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 bottom empty row of the record
Exporter. setparameter (jrxlsexporterparameter. is_one_page_per_sheet, Boolean. False); // Delete redundant columnheader
Exporter. setparameter (jrxlsexporterparameter. is_white_page_background, Boolean. False); // display the 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, and graphs, or display reports

 

Jasperreports introduction:

Using jasperreports to generate a report is very simple. You can use only several classes in the net. SF. jasperreports. Engine package to generate, preview, print, and export a report.

1. net. SF. jasperreports. Engine. jaspercompilemanager class.
You can use several static methods of this class to compile the report (For details, refer to the API documentation)
After compilation, jaspercompilemanager can be processed in two ways:
1> return a jasperreport object
2> Generate a. Jasper file in the directory where the. jrxml file is located.
The two methods are selected by the programmer. However, I prefer to use the. Jasper file. After all, the report structure is not changed every day, so it is not very cost-effective to recompile the report every time.

2. net. SF. jasperreports. Engine. jasperfillmanager class
This class is used to fill the report with data. It can also use the jasperreport object. The Jasper file is used as a report template.
It also has two processing methods:
1> return a jsaperprint object.
2> Generate a. jrprint file in the directory where the. Jasper file is located.
This class uses 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 as needed. Here I use jrtablemodeldatasource
Data Source (because my reports are also displayed in the table ).

3. net. SF. jasperreports. Engine. jasperprintmanager and net. SF. jasperreports. Engine. jasperexportmanager
The two types are used to print and export reports.
They use the jasperprint and. jrprint files as input.
You can use the method as needed.

Example:
Import net. SF. jasperreports. Engine .*;
Import net. SF. jasperreports. View .*;
Public class compilereport {
Public static void main (string ARGs []) {
Try {
// Compile report. jrxml and generate the report. Jasper file in the directory where report. jrxml is located.
Jaspercompilemanager. compilereporttofile ("report. jrxml ");
// Fill in the Data. jremptydatasource is used here.
Jasperfillmanager. fillreporttofile ("report. Jasper", null, new jremptydatasource (50 ));
// Preview the report. False indicates that the XML file is not used.
Jasperviewer view = new jasperviewer ("reports. jrprint", false );
View. Pack ();
View. setvisible (true );
}
Catch (exception e ){
E. printstacktrace ()
}
}
}

 

 

Http://www.heci.net congratulatory Network!]
Jasperreports Study Notes

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

I. Requirements)
Tools and classes used by jasperreports
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 (for database connection)
JDBC 2.0 driver

4. pdf (used for conversion to PDF files)
Itext-free Java-PDF library by Bruno lowagie and Paulo Soares
(Version 1.01 or later)
Http://www.lowagie.com/iText/

5. xls (for converting to an Excel file)
Jakarta poi (Version 2.0 or later)
Http://jakarta.apache.org/poi/

2. Quick how)
1. Main classes (main class)
Main classes 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 many static methods for compiling, filling, printing, and exporting reports. For more information, see the javadoc document of 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 the report design compiling a report Design
The XML file defines the report design ). Generate Reports ). Compile () on the web page to compile the report design ). However, jaspercompilemanager does not approve of using this method to compile report design. We recommend that you use the jaspercompilemanager method compilereportxxx () instead.
When compiling a report design, jasperreports engine first checks the template, determines whether the template is consistent, converts all report expressions, and generates a. Jasper file. To make compilation as flexible as possible, you can implement the net. SF. jasperreports. Engine. Design. jrcompiler interface.

3. Preview report design viewing a report Design
Use the program net. SF. jasperreports. View. jasperdesignviewer to preview. The main () method accepts the report design file name (XML) or the compiled. Jasper file.

4. Fill report filling a report
Compile the report design (XML file) to obtain the report file (. Jasper). Then call the net. SF. jasperreports. Engine. jasperfillmanager class method fillreportxxx () to obtain the report (jasperprint ).
5. Preview The report viewing a report
Generated reports can be viewed using the net. SF. jasperreports. View. jasperviewer application.
In its main () method, it records es the name of the file which contains the report to view.
I did not test successfully.
6. Printing a report
Generated reports can be 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
Fill in the report file (. after obtaining the report (jasperprint), you can use net. SF. jasperreports. engine. the jasperexportmanager class method exportreportxxx () is used to export PDF, HTML, and XML files in various formats.
After having filled a report, we can also export it in PDF, HTML or XML format using the exportreportxxx () Methods of the net. SF. jasperreports. Engine. jasperexportmanager class.

Iii. jasperreports workflow:
 
According to the process, jasperreports provides the following steps for reporting:

1. Report design can be implemented using ireport visualization tools to generate xml files. After completion, you can directly compile the XML file in step 3.
2. If a report design file (XML file) already exists, you can use net. SF. jasperreports. engine. XML. jrxmlloader. the load () method is used to load a report design. This method returns the jasperdesign object. With the jasperdesign object, you can modify the report design, such as adding or deleting fields, adding or deleting variables, and adding or deleting groups, and so on.
3. After completing the report design, you can compile the report design. For the report compilation design, you can use the class net. SF. jasperreports. engine. jaspercompilemanager's compilereport () method can be used to compile an XML file or jasperdesign object to generate a jasperreport object. The jasperreport object can be serialized and saved as a file (usually. jasper file ). Class net. SF. jasperreports. Engine. jaspercompilemanager can also convert a report into a report design file (XML file ). After obtaining the jasperreport object (A jasperreport object can be instantiated from the. Jasper file), The jasperprint object is generated for filling data in the report. The jasperprint object can be serialized and saved as a file. With the jasperprint object, you can print, browse, and convert files to other formats, such as PDF, HTML, XML, xls, and CSV. These operations are the final results we want. Although the jasperprintmanager class can be exported as PDF and XML files, the jasperprintmanager class is not recommended. We recommend that you use the jasperexportmanager class to export PDF, HTML, and XML files. You need to export XLS and CSV files, use a professional export class. net. SF. jasperreports. engine. export. jrxlsexporter class and net. SF. jasperreports. engine. export. jrcsvexporter class
Code segment exported as XLS:
Jrxlsexporter exporter = new jrxlsexporter (); // create an 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

The exported CSV file is similar to the xls file.
 

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.