Java + ireport Application

Source: Internet
Author: User

Ireport:

First, we use ireport to design the report style and generate the. jasper file through compilation to prepare for java.

Second, we define the report public class in java to parse the. jasper file.

Finally, the stream is output to the page.

1. Use ireport to design a simple report: here we use ireport3.0, because 3.0 is relatively stable.

1.1 first, create a report file, such as title, pageHeader, columnHeader... and so on.

650) this. width = 650; "onclick = 'window. open (" http://blog.51cto.com/viewpic.php? Refimg = "+ this. src) 'alt =" "border =" 0 "src =" http://www.bkjia.com/uploads/allimg/131228/1413193A0-0.jpg "/>

1.2. The title column is used for title placement; The pageHeader column is used for subtitle and date placement; The columnHeader column is used for header placement; and the detail column is used for detailed information traversing data display ); the summary column contains graphs and Cross reports. The file structure in the lower left corner includes "Parameters", "fields", and variables. parameters are used to define some static text, values can be passed through the background. Fields define VO attributes and variables are used for calculation;

1.2.1 first, we define a parameter named title. Select the parameter ---> "add" -----> parameter, for example:

650) this. width = 650; "onclick = 'window. open (" http://blog.51cto.com/viewpic.php? Refimg = "+ this. src) 'alt =" "border =" 0 "src =" http://www.bkjia.com/uploads/allimg/131228/14131a415-1.jpg "/>

In the displayed dialog box, enter title in the parameter name, click OK, and drag the title parameter to the title column, for example:

650) this. width = 650; "onclick = 'window. open (" http://blog.51cto.com/viewpic.php? Refimg = "+ this. src) 'alt =" "border =" 0 "src =" http://www.bkjia.com/uploads/allimg/131228/14131914J-2.jpg "/>

Here we can set the font, size, and position of the title.

1.2.2 In the same way, we create two fields: username and password:

650) this. width = 650; "onclick = 'window. open (" http://blog.51cto.com/viewpic.php? Refimg = "+ this. src) 'alt =" "border =" 0 "src =" http://www.bkjia.com/uploads/allimg/131228/1413193295-3.jpg "/>

Drag them to the detail column, and adjust the size, position, and boundary:

650) this. width = 650; "onclick = 'window. open (" http://blog.51cto.com/viewpic.php? Refimg = "+ this. src) 'alt =" "border =" 0 "src =" http://www.bkjia.com/uploads/allimg/131228/1413194Q2-4.jpg "/>

Next we can add a header to the column: click "T" static text in the toolbar and draw it in the columnHeader column:

650) this. width = 650; "onclick = 'window. open (" http://blog.51cto.com/viewpic.php? Refimg = "+ this. src) 'alt =" "border =" 0 "src =" http://www.bkjia.com/uploads/allimg/131228/1413193Y0-5.jpg "/>

The preceding simple report is drawn. Click the "execute Report" button on the toolbar to compile the report to the. jasper file.

1.3. Next we define the java class Reports. java:

Import java. io. ByteArrayOutputStream;
Import java. io. File;
Import java. io. IOException;
Import java. io. PrintWriter;
Import java.net. URLEncoder;
Import java. util. ArrayList;
Import java. util. List;
Import java. util. Map;

Import javax. servlet. ServletOutputStream;
Import javax. servlet. http. HttpServletRequest;
Import javax. servlet. http. HttpServletResponse;

Import net. sf. jasperreports. engine. JRException;
Import net. sf. jasperreports. engine. JRExporterParameter;
Import net. sf. jasperreports. engine. JasperFillManager;
Import net. sf. jasperreports. engine. JasperPrint;
Import net. sf. jasperreports. engine. JasperReport;
Import net. sf. jasperreports. engine. data. JRBeanCollectionDataSource;
Import net. sf. jasperreports. engine. export. JExcelApiExporter;
Import net. sf. jasperreports. engine. export. JRHtmlExporter;
Import net. sf. jasperreports. engine. export. JRHtmlExporterParameter;
Import net. sf. jasperreports. engine. export. JRXlsExporterParameter;
Import net. sf. jasperreports. engine. util. JRLoader;

Public class Reports {
/**//*
* Generate HTML report display
*/
Public void selectHtmlReport (List list, HttpServletResponse response, String url, Map map ){
Response. setContentType ("text/html; charset = UTF-8 ");
File reportFile = new File (url );
JasperReport jasperReport = null;
Try {
JasperReport = (JasperReport) JRLoader. loadObject (reportFile. getPath ());
} Catch (JRException e ){
E. printStackTrace ();
}

JRBeanCollectionDataSource jrbean = new JRBeanCollectionDataSource (list );
JasperPrint jasperPrint = null;
Try {
JasperPrint = JasperFillManager. fillReport (jasperReport, map, jrbean );
} Catch (JRException e ){
E. printStackTrace ();
}
JRHtmlExporter exporter = new JRHtmlExporter ();
PrintWriter out = null;
Try {
Out = response. getWriter ();
} Catch (IOException e ){
E. printStackTrace ();
}
Exporter. setParameter (JRExporterParameter. JASPER_PRINT, jasperPrint );
Exporter. setParameter (JRExporterParameter. OUTPUT_WRITER, out );
Exporter. setParameter (JRHtmlExporterParameter. IS_USING_IMAGES_TO_ALIGN, Boolean. FALSE );
Exporter. setParameter (JRHtmlExporterParameter. IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, Boolean. TRUE );
Try {
Exporter. exportReport ();
} Catch (JRException e ){
E. printStackTrace ();
}
}
/**//*
* Export an EXCEL report
*/
Public void selectExcelReport (List list, HttpServletResponse response, String url, Map map, String reportName ){

Try {
// Load the jasper File
File reportFile = new File (url );
JasperReport jasperReport = (JasperReport) JRLoader. loadObject (reportFile. getPath ());

// Load data
JRBeanCollectionDataSource jrbean = new JRBeanCollectionDataSource (list );

// Construct the jasperPrint object
JasperPrint jasperPrint = JasperFillManager. fillReport (jasperReport, map, jrbean );

// Output stream
ByteArrayOutputStream oStream = new ByteArrayOutputStream ();

// Construct the output object
JExcelApiExporter exporter = new JExcelApiExporter ();
Exporter. setParameter (JRHtmlExporterParameter. IMAGES_URI, "./image? Image = ");
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 ();

// Excel file name
String fileName = reportName + ". xls ";
Response. reset ();
Response. setHeader ("Content-Disposition", "attachment; filename = \" "+ URLEncoder. encode (fileName," UTF-8 ") + "\"");
// Write output stream
Byte [] bytes = oStream. toByteArray ();
If (bytes! = Null & bytes. length> 0 ){
Response. setContentType ("application/vnd. ms-excel; charset = UTF-8 ");
Response. setContentLength (bytes. length );
ServletOutputStream ouputStream = response. getOutputStream ();
OuputStream. write (bytes, 0, bytes. length );
OuputStream. flush ();
OuputStream. close ();
} Else {
}
} Catch (Exception ex ){
Ex. printStackTrace ();
}
}
/**
* Function: processing method for generating default graph reports
* Method name: selectHtmlReport
* @ Param List list Dataset
* @ Param HttpServletResponse response
* @ Param HttpServletRequest request
* @ Param String the report file parsed by the url
* @ Param Map parameters used in the map report
* @ Author Guo Hongzhi 2010-03-15
* @ Return void
*/
Public void selectHtmlReport (List list, HttpServletResponse response, HttpServletRequest request, String url, Map map ){
Response. setContentType ("text/html; charset = UTF-8 ");
File reportFile = new File (url );
JasperReport jasperReport = null;
Try {
JasperReport = (JasperReport) JRLoader. loadObject (reportFile. getPath ());
} Catch (JRException e ){
E. printStackTrace ();
}
JRBeanCollectionDataSource jrbean = new JRBeanCollectionDataSource (list );
JasperPrint jasperPrint = null;
// Set the default storage directory for report graphics
String outPutDir = request. getSession (). getServletContext (). getRealPath ("/") + "/reportimg /";
// Load the relative directory of the graphic report
String sourceDir = request. getContextPath () + "/reportimg /";
Try {
File file = new File (outPutDir );
// Determine whether the directory exists
If (! File. exists ()){
File. mkdir ();
}
JasperPrint = JasperFillManager. fillReport (jasperReport, map, jrbean );
} Catch (JRException e ){
E. printStackTrace ();
}
JRHtmlExporter exporter = new JRHtmlExporter ();
PrintWriter out = null;
Try {
Out = response. getWriter ();
} Catch (IOException e ){
E. printStackTrace ();
}

Exporter. setParameter (JRHtmlExporterParameter. IMAGES_DIR_NAME, outPutDir );
Exporter. setParameter (JRHtmlExporterParameter. IMAGES_URI, sourceDir );
Exporter. setParameter (JRHtmlExporterParameter. IS_OUTPUT_IMAGES_TO_DIR, Boolean. TRUE );
Exporter. setParameter (JRExporterParameter. OUTPUT_WRITER, out );
Exporter. setParameter (JRExporterParameter. JASPER_PRINT, jasperPrint );
Exporter. setParameter (JRHtmlExporterParameter. IS_USING_IMAGES_TO_ALIGN, Boolean. FALSE );
Exporter. setParameter (JRHtmlExporterParameter. IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, Boolean. TRUE );
Try {
Exporter. exportReport ();
} Catch (JRException e ){
E. printStackTrace ();
}
}
/**
* Function: generate a query method for a graphic report of a specified directory.
* @ Param List list Dataset
* @ Param HttpServletResponse response
* @ Param HttpServletRequest request
* @ Param String the report file parsed by the url
* @ Param Map parameters used in the map report
* @ Param String the directory generated by the imgDir Graph
* @ Author Guo Hongzhi 2010-01-20
* @ Return void
*/
Public void selectHtmlReport (List list, HttpServletResponse response, HttpServletRequest request, String url, Map map, String imgDir ){
Response. setContentType ("text/html; charset = UTF-8 ");
File reportFile = new File (url );
JasperReport jasperReport = null;
// Generate a graphical directory
String outPutDir = request. getSession (). getServletContext (). getRealPath ("/") + "/" + imgDir;
// Graphical source directory
String sourceDir = request. getContextPath () + "/" + imgDir;
Try {
JasperReport = (JasperReport) JRLoader. loadObject (reportFile. getPath ());
} Catch (JRException e ){
E. printStackTrace ();
}

JRBeanCollectionDataSource jrbean = new JRBeanCollectionDataSource (list );
JasperPrint jasperPrint = null;
Try {
JasperPrint = JasperFillManager. fillReport (jasperReport, map, jrbean );
} Catch (JRException e ){
E. printStackTrace ();
}
JRHtmlExporter exporter = new JRHtmlExporter ();
PrintWriter out = null;
Try {
Out = response. getWriter ();
} Catch (IOException e ){
E. printStackTrace ();
}
// Set the physical directory for storing images
Exporter. setParameter (JRHtmlExporterParameter. IMAGES_DIR_NAME, outPutDir );
// Set the image display directory
Exporter. setParameter (JRHtmlExporterParameter. IMAGES_URI, sourceDir );
// Generate an image to the directory
Exporter. setParameter (JRHtmlExporterParameter. IS_OUTPUT_IMAGES_TO_DIR, Boolean. TRUE );
Exporter. setParameter (JRExporterParameter. JASPER_PRINT, jasperPrint );
Exporter. setParameter (JRExporterParameter. OUTPUT_WRITER, out );
Exporter. setParameter (JRHtmlExporterParameter. IS_USING_IMAGES_TO_ALIGN, Boolean. FALSE );
Exporter. setParameter (JRHtmlExporterParameter. IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, Boolean. TRUE );
Try {
Exporter. exportReport ();
} Catch (JRException e ){
E. printStackTrace ();
}
}
/**
* Function: How to export multi-sheet reports
* Method name: selectAllExcelReport
* @ Param List list Dataset
* @ Param HttpServletResponse response
* @ Param String the report file parsed by the url
* @ Param String reportName: generate the name saved in excel
* @ Author Guo Hongzhi
* Creation Time: Nov 3, 2009 2:08:31
*/
@ SuppressWarnings ("unchecked ")
Public void selectAllExcelReport (List list, HttpServletResponse response, String url, String reportName ){
Try {
// Load the jasper File
File reportFile = new File (url );
JasperReport jasperReport = (JasperReport) JRLoader. loadObject (reportFile. getPath ());
List jasperPrintList = new ArrayList ();

Int listSize = list. size ();
String sheetNamesArray [] = new String [listSize];
For (int I = 0; I <listSize; I ++ ){
Map eachMap = (Map) list. get (I );
List eachList = (List) eachMap. get ("ls ");
SheetNamesArray [I] = (String) eachMap. get ("title ");
// Load data
JRBeanCollectionDataSource jrbean = new JRBeanCollectionDataSource (eachList );
// Construct the jasperPrint object
JasperPrint jasperPrint = JasperFillManager. fillReport (jasperReport, eachMap, jrbean );
JasperPrintList. add (jasperPrint );
}

// Output stream
ByteArrayOutputStream oStream = new ByteArrayOutputStream ();

// Construct the output object
JExcelApiExporter exporter = new JExcelApiExporter ();
Exporter. setParameter (JRHtmlExporterParameter. IMAGES_URI, "./image? Image = ");
Exporter. setParameter (JRExporterParameter. JASPER_PRINT_LIST, jasperPrintList );
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. setParameter (JRXlsExporterParameter. SHEET_NAMES, sheetNamesArray );
Exporter. exportReport ();

// Write output stream
Byte [] bytes = oStream. toByteArray ();
If (bytes! = Null & bytes. length> 0 ){
Response. reset ();
Response. setContentType ("application/vnd. ms-excel; charset = UTF-8 ");
Response. setContentLength (bytes. length );
// Excel file name
String fileName = reportName + ". xls ";
Response. setHeader ("Content-Disposition", "attachment; filename = \" "+ URLEncoder. encode (fileName," UTF-8 ") + "\"");
ServletOutputStream ouputStream = response. getOutputStream ();
OuputStream. write (bytes, 0, bytes. length );
OuputStream. flush ();
OuputStream. close ();
}
} Catch (Exception ex ){
Ex. printStackTrace ();
}
}
}
1.4, called in action:

Map <String, String> parameters = new HashMap <String, String> (); // defines the parameter map

Parameters. put ("title", "My reports"); // Add parameters

String url = "WEB-INF/report/test. jasper"; // define the report file path

Reports report = new Reports (); // create a report object

Report. selectHtmlReport (List, Response, url, parameters); // call the table generation method.

Here, list is the value queried from the database, and the VO object is put. The VO object attributes correspond to the fields defined in the. jasper report file one by one.

The definition of VO class is omitted here.

How to export a report call: report. selectExcelReport (list, response, url, parameters );

 

This article is from the "Zijing phantom Governance" blog and will not be reposted!

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.