我们上一次成功的利用iReport工具制作了一张报表,并且预览了报表最后的效果,也生成了格式为“jrpxml”、“jrxml”与“jasper”的文件。这次,我们使用jasper提供的java的api去利用在iReport中制作的报表jasper文件来生成真正的报表文件。
本文以生成pdf格式的报表文件为例,该报表文件包含所有男用户的信息。
首先我们打开MyEclipse,在其中创建一个java工程:
新建一个lib文件夹,然后在lib中加入我们准备好的jar包:
然后将这些jar包全部添加到环境中(右键build path)
然后编写获取数据库连接的类,用于连接数据库并获取相应连接对象,以便于后期操作数据库:
- packagecom.cn.org.ireport.test;
- importjava.sql.Connection;
- importjava.sql.DriverManager;
- publicclassJDBCConnection{
- publicstaticConnectiongetConnection(){
- try{
- Stringurl="jdbc:mysql://localhost:3306/db_film";
- Class.forName("org.gjt.mm.mysql.Driver");
- Connectioncon=DriverManager.getConnection(url,"root","1234");
- returncon;
- }catch(Exceptione){
- e.printStackTrace();
- }
- returnnull;
- }
- }
接下来编写dataSource类(也就是数据填充类),实现JRDataSource接口,通过放在list里面的Map对象迭代实现数据对应:
- packagecom.cn.org.ireport.test;
- importjava.util.HashMap;
- importjava.util.Iterator;
- importjava.util.List;
- importjava.util.Map;
- importnet.sf.jasperreports.engine.JRDataSource;
- importnet.sf.jasperreports.engine.JRException;
- importnet.sf.jasperreports.engine.JRField;
- /**
- *dataSource类(也就是数据填充类),实现JRDataSource接口
- *通过放在list里面的Map对象迭代,实现数据对应
- */
- publicclassReportDataSourceimplementsJRDataSource{
- privateIteratoriter;
- //创建一个,map对象用与数据对应
- Mapmap=newHashMap();
- //无参的构造函数
- publicReportDataSource(){
- }
- //以sex为参数的有参构造函数,用于数据初始化
- publicReportDataSource(Stringsex){
- //通过性别获取相应用户的数据
- Listdatas=DateSourceBaseFactory.createBeanCollection(sex);
- //要将List中的数据迭代,需要使用Iterator迭代对象
- iter=datas.iterator();
- }
- //通过key获取value值
- publicObjectgetFieldValue(JRFieldarg0)throwsJRException{
- returnmap.get(arg0.getName());
- }
- //接口JRDataSource的方法,判断是否有下一个数据
- publicbooleannext()throwsJRException{
- if(iter.hasNext()){
- map=(Map)iter.next();
- returntrue;
- }
- returnfalse;
- }
- }
接下来实现上个类中的DateSourceBaseFactory(提供数据的数据源工厂),它是实际从数据库中取出相应数据,然后将其封装在map中,然后又将相应的map装在List容器中。
- packagecom.cn.org.ireport.test;
- importjava.sql.Connection;
- importjava.sql.ResultSet;
- importjava.sql.SQLException;
- importjava.sql.Statement;
- importjava.util.ArrayList;
- importjava.util.HashMap;
- importjava.util.List;
- importjava.util.Map;
- /**
- *Map中的键值要与模板中的file值对应
- **/
- publicclassDateSourceBaseFactory{
- publicstaticListcreateBeanCollection(Stringsex){
- intnum=0;
- if(sex.equals("男")){
- num=1;
- }else{
- num=2;
- }
- ResultSetrs=null;
- Statementst=null;
- Connectioncon=null;
- Listdatas=newArrayList();
- try{
- con=JDBCConnection.getConnection();
- st=con.createStatement();
- rs=st.executeQuery("selectname,brithday,province,Emailfromuserwheresex="+num);
- while(rs.next()){
- Mapattris=newHashMap();
- attris.put("name",rs.getString("name"));
- attris.put("brithday",rs.getString("brithday"));
- attris.put("province",rs.getString("province"));
- attris.put("Email",rs.getString("Email"));
- datas.add(attris);
- }
- }catch(Exceptione){
- e.printStackTrace();
- }finally{
- try{
- if(rs!=null)rs.close();
- if(st!=null)st.close();
- if(con!=null)con.close();
- }catch(SQLExceptione){
- e.printStackTrace();
- }
- }
- returndatas;
- }
- }
接下来编写dataSource的javaBean类。用于创建模板
- packagecom.cn.org.ireport.test;
- importjava.io.Serializable;
- publicclassDataSoruceBeanimplementsSerializable{
- privatestaticfinallongserialVersionUID=1L;
- privateStringname;
- privateStringbrithday;
- privateStringprovince;
- privateStringEmail;
- publicStringgetName(){
- returnname;
- }
- publicvoidsetName(Stringname){
- this.name=name;
- }
- publicStringgetBrithday(){
- returnbrithday;
- }
- publicvoidsetBrithday(Stringbrithday){
- this.brithday=brithday;
- }
- publicStringgetProvince(){
- returnprovince;
- }
- publicvoidsetProvince(Stringprovince){
- this.province=province;
- }
- publicStringgetEmail(){
- returnthis.Email;
- }
- publicvoidsetEmail(Stringemail){
- this.Email=email;
- }
- }
接下来是重头戏,编写测试入口类,生成pdf文件。JasperFillManager中有多个生成文件的方法
,除了可以生成pdf文件外还可以生成ofice文档文件。这里我们就将取出的数据打印到报表中去:
- packagecom.cn.org.ireport.test;
- importjava.io.ByteArrayOutputStream;
- importjava.io.File;
- importjava.io.FileOutputStream;
- importjava.util.HashMap;
- importjava.util.Map;
- importnet.sf.jasperreports.engine.JRAbstractExporter;
- importnet.sf.jasperreports.engine.JRException;
- importnet.sf.jasperreports.engine.JRExporterParameter;
- importnet.sf.jasperreports.engine.JasperFillManager;
- importnet.sf.jasperreports.engine.JasperPrint;
- importnet.sf.jasperreports.engine.export.JRPdfExporter;
- importnet.sf.jasperreports.engine.export.JRPdfExporterParameter;
- publicclassTestReportHere{
- publicstaticvoidmain(String[]args){
- Mapparameters=newHashMap();
- ByteArrayOutputStreamoutPut=newByteArrayOutputStream();
- FileOutputStreamoutputStream=null;
- Filefile=newFile("F:/Temp/report.pdf");
- StringreportModelFile="C:/Users/jack/report2.jasper";
- try{
- JasperPrintjasperPrint=JasperFillManager.fillReport(reportModelFile,
- parameters,newReportDataSource("男"));
- JRAbstractExporterexporter=newJRPdfExporter();
- //创建jasperPrint
- exporter.setParameter(JRExporterParameter.JASPER_PRINT,jasperPrint);
- //生成输出流
- exporter.setParameter(JRExporterParameter.OUTPUT_STREAM,outPut);
- //屏蔽copy功能
- exporter.setParameter(JRPdfExporterParameter.IS_ENCRYPTED,Boolean.TRUE);
- //加密
- exporter.setParameter(JRPdfExporterParameter.IS_128_BIT_KEY,Boolean.TRUE);
- exporter.exportReport();
- outputStream=newFileOutputStream(file);
- outputStream.write(outPut.toByteArray());
- }catch(JRExceptione){
- e.printStackTrace();
- }catch(Exceptione){
- e.printStackTrace();
- }finally{
- try{
- outPut.flush();
- outPut.close();
- }catch(Exceptione){
- e.printStackTrace();
- }
- }
- }
- }
我们点击右键“Run JavaAppliacrion”,来执行我们的报表生成样例。
运行结果,我们在F盘下的Temp下发现了新生成的pdf文件:
双击打开,就是我们之前需要的数据的报表信息。
注意:报表Pdf时,会出现中文无法显示问题,可以设置相关组件的以下属性。需同时设置,其他字体,可自行尝试。
1、Font name :宋体
2、pdf Font name is now deprecated:STSong-Light
3、pdf Encoding : UniGB-UCS2-H(China Simplified)
至此我们实现了使用jasper提供的java的api来实现封装数据打印报表的功能。
直接在网页上下载这个PDF格式文件
/**
* 输出jasper 报表
*
* @param reportHanderImpi
* @throws AppException
*/
public void exportReport(ReportHanderImpl reportHanderImpl)
throws AppException {
this.getRequest().setAttribute(ReportConstants.REPORT_FLAG, "0");
this.getRequest().setAttribute(ReportConstants.REPORT_PATH_SYMBOL,
reportHanderImpl.getReportFile());
if(reportHanderImpl instanceof CommonReportHandler){
// 报表文件的输入流
this.getRequest().setAttribute(ReportConstants.REPORT_INPUTSTREAM,
((CommonReportHandler)reportHanderImpl).getReportInputStream());
}
List datalist = reportHanderImpl.getDataList();
JRDataSource dataSource = null;
if (datalist != null && datalist.size()>0) {
dataSource = new JRBeanCollectionDataSource(datalist);// 获取数据集
} else {
dataSource = new JREmptyDataSource();
}
this.getRequest().setAttribute(
ReportConstants.REPORT_DATASOURCE_SYMBOL, dataSource);
this.getRequest().setAttribute(ReportConstants.DISPLAY_FIELDS_SYMBOL,
reportHanderImpl.getDisplayStr());
//获取报表类型(表格 or 图形)
this.getRequest().setAttribute( ReportConstants.REPORT_TYPE_SYMBOL, reportHanderImpl.getReportType());
//报表输出格式类型(PDF or EXCEL ,HTML)
this.getRequest().setAttribute( ReportConstants.REPORT_OUT_FORMAT_SYMBOL, reportHanderImpl.getFormatType());
this.getRequest().setAttribute(ReportConstants.REPORT_PARAMETER_SYMBOL,
reportHanderImpl.getParamMap());
try {
this.getRequest().getRequestDispatcher("/JReportServlet").forward(
ServletActionContext.getRequest(),
ServletActionContext.getResponse());
} catch (ServletException e) {
new AppException(e);
} catch (IOException e) {
new AppException(e);
}
}
EG2:
@SuppressWarnings("rawtypes")
public void exportReportList1(CommonReportHandler commonReportHandler)
throws AppException {
List lst = commonReportHandler.getDataSourceList();
List<Object> dataSourceList = null;
try {
if (lst != null && lst.size() > 0) {
dataSourceList = new ArrayList<Object>();
JRDataSource dataSource = null;
for (int i = 0; i < lst.size(); i++) {
List datalist = (List) lst.get(i);
if (datalist != null && datalist.size() > 0) {
dataSource = new JRBeanCollectionDataSource(datalist);// 获取数据集
} else {
dataSource = new JREmptyDataSource();
}
dataSourceList.add(dataSource);// 组装数据源集合
}
}
this.getRequest().setAttribute(ReportConstants.REPORT_FLAG, "1");
// 设置路径
this.getRequest().setAttribute(
ReportConstants.REPORT_PATHLIST_SYMBOL,
commonReportHandler.getReportFiles());
// 获取报表类型(表格 or 图形)
this.getRequest().setAttribute("ReportType", "GraphicsReport");
// 报表输出格式类型(PDF or EXCEL ,HTML)
this.getRequest().setAttribute(
ReportConstants.REPORT_OUT_FORMAT_SYMBOL,
commonReportHandler.getFormatType());
// 设置数据源LIST
this.getRequest().setAttribute(
ReportConstants.REPORT_DATASOURCELIST_SYMBOL,
dataSourceList);
// 设置MAP参数
this.getRequest().setAttribute(
ReportConstants.REPORT_PARAMETER_SYMBOL,
commonReportHandler.getParamMap());
this.getRequest()
.getRequestDispatcher("/JReportServlet")
.forward(ServletActionContext.getRequest(),
ServletActionContext.getResponse());
} catch (ServletException e) {
throw new AppException(e);
} catch (IOException e) {
throw new AppException(e);
}
}
打印信息,通过.jasper工具将集合输出到PDF文件 然后利用打印机打印文件
原文地址:https://www.cnblogs.com/UUUz/p/9167565.html