jasperReports+ireport+java运用

jasperReports+ireport+java运用

模板工具版本:iReport-5.6.0
参考文献:http://blog.csdn.net/frankaqi/article/details/50203877


  • jasperReportsireportjava运用
    • 一 简单的数据展示和表格运用
    • 二 char图形运用
      • 饼图运用
      • 条线图
      • 折线图
    • 三 子数据源
      • 创建子数据源在Report Inspector窗口选中项目右键菜单选择Add Dataset
      • 子数据源增加 Fields数据
      • 运用以饼图3D为例
    • 实例环境
    • 显示常用设置

一: 简单的数据展示和表格运用

1.创建VO用以装载table数据

public class TableVo extends BaseBean{
       private static final long serialVersionUID = 1L;
      //ID
    private String id;
         //名称
    private String name;
    //类别
    private String lable;
    //数值
    private long number;
    //是否显示
    private boolean showFlag;

    ....................

2.在ireport创建一个空白模板
jasperReports+ireport+java运用_第1张图片

jasperReports+ireport+java运用_第2张图片

jasperReports+ireport+java运用_第3张图片

3.根据第一步中的VO创建与VO中对应的Fields对象(对象数据类型必须一一对应)

jasperReports+ireport+java运用_第4张图片

4.设计模板
4.1 设置报表标题,和其他参数,标题和其他lable选择static Text组件;参数型数据选择Text Field组件

jasperReports+ireport+java运用_第5张图片

4.2 table部分设计
Column Header 为表头设计部分,Detail为数据明细部分,注意调整高度;可删除模板中不用的部分入Page Header,page Footer等区域
jasperReports+ireport+java运用_第6张图片

若要为table设置边框则在模板设计时选中组件点击右键选择 Padding and Border

jasperReports+ireport+java运用_第7张图片

4.3其他设置
4.3.1.解决pdf导出中文显示问题:选中所有组件

jasperReports+ireport+java运用_第8张图片

4.3.2参数值为空时显示为null解决办法

jasperReports+ireport+java运用_第9张图片

5.模板制作完成生成.jasper文件
5.1设置导出位置:工具》选项

jasperReports+ireport+java运用_第10张图片

5.2点击preview预览则能生成模板文件

jasperReports+ireport+java运用_第11张图片

6.导出测试
6.1将模板上传至工程相应目录

jasperReports+ireport+java运用_第12张图片

6.2设置模板数据,装载模板
jasperReports+ireport+java运用_第13张图片
jasperReports+ireport+java运用_第14张图片

jasperReports+ireport+java运用_第15张图片

添加表格求和统计:添加variables

jasperReports+ireport+java运用_第16张图片

jasperReports+ireport+java运用_第17张图片

使用:

jasperReports+ireport+java运用_第18张图片

二: char图形运用

summary区域设置图形

1.饼图运用

jasperReports+ireport+java运用_第19张图片

jasperReports+ireport+java运用_第20张图片

在饼图区域点击右键》chart data 将Filter Expression值设置为$F{showFlag}控制显示项

jasperReports+ireport+java运用_第21张图片

设置描述区域项目

jasperReports+ireport+java运用_第22张图片

最后生成模板放入工程,
jasperReports+ireport+java运用_第23张图片
jasperReports+ireport+java运用_第24张图片

若showFlag全为true,则存在多组数据,饼图会显示最后一组数据;

2.条线图

jasperReports+ireport+java运用_第25张图片
jasperReports+ireport+java运用_第26张图片
jasperReports+ireport+java运用_第27张图片

Series expression用来区分曲线
Category expression是横坐标
Value expression是纵坐标

展示效果:

jasperReports+ireport+java运用_第28张图片

3.折线图

jasperReports+ireport+java运用_第29张图片

配置与条形图相似,看下效果
jasperReports+ireport+java运用_第30张图片

三: 子数据源

子数据源可运用于作为各个组件的数据源

1.创建子数据源:在“Report Inspector”窗口,选中项目右键菜单选择”Add Dataset“

jasperReports+ireport+java运用_第31张图片

jasperReports+ireport+java运用_第32张图片

2.子数据源增加 Fields数据

jasperReports+ireport+java运用_第33张图片

3.运用,以饼图(3D)为例:

jasperReports+ireport+java运用_第34张图片

jasperReports+ireport+java运用_第35张图片

jasperReports+ireport+java运用_第36张图片

在饼图区域点击右键》chart data配置子数据源的数据来源

jasperReports+ireport+java运用_第37张图片

new net.sf.jasperreports.engine.data.JRBeanCollectionDataSource($P{REPORT_PARAMETERS_MAP}.get( “chart1” ))

此处参数“chart1”与java中的传的参数一致

jasperReports+ireport+java运用_第38张图片

效果:

jasperReports+ireport+java运用_第39张图片

实例环境

maven引入jasper所需jar包

        
    
    
        net.sf.jasperreports
        jasperreports
        6.0.0
    
    
    
       com.itextpdf  
       itextpdf  
       5.5.11  
     
     
       com.itextpdf  
       itext-pdfa  
       5.5.11  
     
     
       com.itextpdf  
       itext-asian  
       5.2.0  
     
   
   
     org.codehaus.groovy
     groovy-all
     2.4.13
       
   

数据源主要代码:


          .....................

TableVo report = new TableVo();  
          List reports = new ArrayList();    
          //装载数据  
          report.setId("1");//测试为空时,
          report.setName("测1");
          report.setNumber(6);
          report.setLable("第一类");
          report.setShowFlag(true);
          reports.add(report);

          report = new TableVo(); 
          report.setId("2");
          report.setName("测2");
          report.setNumber(2);
          report.setLable("第一类");
          report.setShowFlag(true);
          reports.add(report);

          report = new TableVo(); 
          report.setId("3");
          report.setName("测3");
          report.setNumber(3);
          report.setLable("第一类");
          report.setShowFlag(true);
          reports.add(report);

          report = new TableVo(); 
          report.setId("4");
          report.setName("测1");
          report.setNumber(1);
          report.setLable("第二类");
          report.setShowFlag(true);
          reports.add(report);

          report = new TableVo();           
          report.setId("5");
          report.setName("测2");
          report.setNumber(4);
          report.setLable("第二类");
          report.setShowFlag(true);
          reports.add(report);

          report = new TableVo();           
          report.setId("6");
          report.setName("测3");
          report.setNumber(15);
          report.setLable("第二类");
          report.setShowFlag(true);
          reports.add(report);

          //JRBeanCollectionDataSource通过构造注入collection类型的参数,这里我们用的是list结构  
          JRDataSource jrDataSource = new JRBeanCollectionDataSource(reports);
         //构建参数map 
          Map map=new HashMap();
          map.put("query", "其他参数测试"); 
          //子数据源测试
          map.put("chart1", reports);
          //指定模板文件
        ServletContext context = request.getSession().getServletContext();
        File reportFile = null;
        reportFile = new File(context.getRealPath("/pages/jasper/table_test.jasper"));
        //指定导出文件名称
        String exportFilePath = "table导出测试";
        //调用工具类
        JasperHelper.showPdf(exportFilePath, reportFile.getPath(), request, response, map,jrDataSource);
        //JasperHelper.showHtml(exportFilePath , reportFile.getPath(), request,response, map, jrDataSource);        
        //JasperHelper.export("excel", exportFilePath, reportFile, request, response, map, jrDataSource);

    ........................        

报表生成工具类JasperHelper :

package XXXXX;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.util.Map;

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

import net.sf.jasperreports.engine.JRAbstractExporter;
import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporter;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.base.JRBaseReport;
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.JRPdfExporter;
import net.sf.jasperreports.engine.export.JRRtfExporter;
import net.sf.jasperreports.engine.export.JRXlsExporter;
import net.sf.jasperreports.engine.export.JRXlsExporterParameter;
import net.sf.jasperreports.engine.export.JRXmlExporter;
import net.sf.jasperreports.engine.util.JRLoader;
import net.sf.jasperreports.j2ee.servlets.ImageServlet;

import org.apache.log4j.Logger;

import java.sql.Connection;

@SuppressWarnings("deprecation")
public class JasperHelper {
    private static Logger logger = Logger.getLogger(JasperHelper.class);
    public static final String PRINT_TYPE = "print";
    public static final String PDF_TYPE = "pdf";
    public static final String EXCEL_TYPE = "excel";
    public static final String HTML_TYPE = "html";
    public static final String WORD_TYPE = "word";

    public static void prepareReport(JasperReport jasperReport, String type) {
        logger.debug("The method======= prepareReport() start.......................");
        /*
         * 如果导出的是excel,则需要去掉周围的margin
         */
        if ("excel".equals(type))
            try {
                Field margin = JRBaseReport.class
                        .getDeclaredField("leftMargin");
                margin.setAccessible(true);
                margin.setInt(jasperReport, 0);
                margin = JRBaseReport.class.getDeclaredField("topMargin");
                margin.setAccessible(true);
                margin.setInt(jasperReport, 0);
                margin = JRBaseReport.class.getDeclaredField("bottomMargin");
                margin.setAccessible(true);
                margin.setInt(jasperReport, 0);
                Field pageHeight = JRBaseReport.class
                        .getDeclaredField("pageHeight");
                pageHeight.setAccessible(true);
                pageHeight.setInt(jasperReport, 2147483647);
            } catch (Exception exception) {
            }
    }

    /**
     * 导出excel
     */
    public static void exportExcel(JasperPrint jasperPrint,
            String defaultFilename, HttpServletRequest request,
            HttpServletResponse response) throws IOException, JRException {
        /*
         * 设置头信息
         */
        response.setContentType("application/vnd.ms-excel");
        String defaultname = null;
        if (defaultFilename.trim() != null && defaultFilename != null) {
            defaultname = defaultFilename + ".xls";
        } else {
            defaultname = "export.xls";
        }

        response.setHeader("Content-Disposition", "attachment; filename=\""
                + URLEncoder.encode(defaultname, "UTF-8") + "\"");


        ServletOutputStream ouputStream = response.getOutputStream();
        JRXlsExporter exporter = new JRXlsExporter();

        exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);

        exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, ouputStream);

        exporter.setParameter(
                JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS,
                Boolean.TRUE); // 删除记录最下面的空行

        exporter.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET,
                Boolean.FALSE);// 删除多余的ColumnHeader
        //
        exporter.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND,
                Boolean.FALSE);// 显示边框
        exporter.exportReport();
        ouputStream.flush();
        ouputStream.close();
    }

    public static enum DocType {
        PDF, HTML, XLS, XML, RTF
    }
    @SuppressWarnings("rawtypes")
    public static JRAbstractExporter getJRExporter(DocType docType) {
        JRAbstractExporter exporter = null;
        switch (docType) {
        case PDF:
            exporter = new JRPdfExporter();
            break;
        case HTML:
            exporter = new JRHtmlExporter();
            break;
        case XLS:
            exporter = new JExcelApiExporter();
            break;
        case XML:
            exporter = new JRXmlExporter();
            break;
        case RTF:
            exporter = new JRRtfExporter();
            break;
        }
        return exporter;
    }
    /**
     * 导出pdf,注意此处中文问题,
     * 
     * 这里应该详细说:主要在ireport里变下就行了。看图
     * 
     * 1)在ireport的classpath中加入iTextAsian.jar 2)在ireport画jrxml时,看ireport最左边有个属性栏。
     * 
     * 下边的设置就在点字段的属性后出现。 pdf font name :STSong-Light ,pdf encoding :UniGB-UCS2-H
     */
    private static void exportPdf(JasperPrint jasperPrint,
            String defaultFilename, HttpServletRequest request,
            HttpServletResponse response) throws IOException, JRException {
        response.setContentType("application/pdf");
        String defaultname = null;
        if (defaultFilename.trim() != null && defaultFilename != null) {
            defaultname = defaultFilename + ".pdf";
        } else {
            defaultname = "export.pdf";
        }
        String fileName = new String(defaultname.getBytes("GBK"), "ISO8859_1");
        response.setHeader("Content-disposition", "attachment; filename="
                + fileName);
        ServletOutputStream ouputStream = response.getOutputStream();
        JasperExportManager.exportReportToPdfStream(jasperPrint, ouputStream);
        ouputStream.flush();
        ouputStream.close();
    }

    /**
     * 导出html
     */
    private static void exportHtml(JasperPrint jasperPrint,
            String defaultFilename, HttpServletRequest request,
            HttpServletResponse response) throws IOException, JRException {
        response.setContentType("text/html");
        ServletOutputStream ouputStream = response.getOutputStream();
        JRHtmlExporter exporter = new JRHtmlExporter();
        exporter.setParameter(JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN,
                Boolean.FALSE);
        exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
        exporter.setParameter(JRExporterParameter.CHARACTER_ENCODING, "UTF-8");
        exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, ouputStream);
        //设置图片文件存放路径,此路径为服务器上的绝对路径
        String imageDIR =request.getSession().getServletContext().getRealPath("/");
        exporter.setParameter(JRHtmlExporterParameter.IMAGES_DIR_NAME, imageDIR);

        //设置图片请求URI
        String imageURI = request.getContextPath() + "/";
        exporter.setParameter(JRHtmlExporterParameter.IMAGES_URI, imageURI);

        //设置导出图片到图片存放路径
        exporter.setParameter(JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN, Boolean.TRUE);
        exporter.setParameter(JRHtmlExporterParameter.IS_OUTPUT_IMAGES_TO_DIR, Boolean.TRUE); 

        exporter.exportReport();

        ouputStream.flush();
        ouputStream.close();
    }

    /**
     * 导出word
     */
    @SuppressWarnings("rawtypes")
    private static void exportWord(JasperPrint jasperPrint,
            String defaultFilename, HttpServletRequest request,
            HttpServletResponse response) throws JRException, IOException {
        response.setContentType("application/msword;charset=utf-8");
        String defaultname = null;
        if (defaultFilename.trim() != null && defaultFilename != null) {
            defaultname = defaultFilename + ".doc";
        } else {
            defaultname = "export.doc";
        }
        String fileName = new String(defaultname.getBytes("GBK"), "utf-8");
        response.setHeader("Content-disposition", "attachment; filename="
                + fileName);
        JRExporter exporter = new JRRtfExporter();
        exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
        exporter.setParameter(JRExporterParameter.OUTPUT_STREAM,
                response.getOutputStream());

        exporter.exportReport();
    }

    /**
     * 按照类型导出不同格式文件
     * 
     * @param datas
     *            数据
     * @param type
     *            文件类型
     * @param is
     *            jasper文件的来源
     * @param request
     * @param response
     * @param defaultFilename默认的导出文件的名称
     */
    public static void export(String type, String defaultFilename, File is,
            HttpServletRequest request, HttpServletResponse response,
            Map parameters, Connection conn) {
        try {
            JasperReport jasperReport = (JasperReport) JRLoader.loadObject(is);
            prepareReport(jasperReport, type);

            JasperPrint jasperPrint = JasperFillManager.fillReport(
                    jasperReport, parameters, conn);

            if (EXCEL_TYPE.equals(type)) {
                exportExcel(jasperPrint, defaultFilename, request, response);
            } else if (PDF_TYPE.equals(type)) {
                exportPdf(jasperPrint, defaultFilename, request, response);
            } else if (HTML_TYPE.equals(type)) {
                exportHtml(jasperPrint, defaultFilename, request, response);
            } else if (WORD_TYPE.equals(type)) {
                exportWord(jasperPrint, defaultFilename, request, response);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static void export(String type, String defaultFilename, File is,
            HttpServletRequest request, HttpServletResponse response,
            Map parameters, JRDataSource conn) {
        try {
            JasperReport jasperReport = (JasperReport) JRLoader.loadObject(is);
            prepareReport(jasperReport, type);

            JasperPrint jasperPrint = JasperFillManager.fillReport(
                    jasperReport, parameters, conn);

            if (EXCEL_TYPE.equals(type)) {
                exportExcel(jasperPrint, defaultFilename, request, response);
            } else if (PDF_TYPE.equals(type)) {
                exportPdf(jasperPrint, defaultFilename, request, response);
            } else if (HTML_TYPE.equals(type)) {
                exportHtml(jasperPrint, defaultFilename, request, response);
            } else if (WORD_TYPE.equals(type)) {
                exportWord(jasperPrint, defaultFilename, request, response);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 输出html静态页面,必须注入request和response
     * 
     * @param jasperPath
     * @param params
     * @param sourceList
     * @param imageUrl
     *            报表文件使用的图片路径,比如 ../servlets/image?image=
     * @throws JRException
     * @throws IOException
     * @throws ServletException
     */
    public static void showHtml(String defaultFilename, String reportfile,
            HttpServletRequest request, HttpServletResponse response, Map parameters,
            JRDataSource conn) throws JRException, IOException {


        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html");

        JRAbstractExporter exporter = getJRExporter(DocType.HTML);

        JasperPrint jasperPrint = JasperFillManager.fillReport(reportfile,
                parameters, conn);
        request.getSession().setAttribute(
                ImageServlet.DEFAULT_JASPER_PRINT_SESSION_ATTRIBUTE,
                jasperPrint);

        PrintWriter out = response.getWriter();

        exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
        exporter.setParameter(JRExporterParameter.OUTPUT_WRITER, out);
        exporter.setParameter(
        JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN,
        Boolean.FALSE);

        //设置图片文件存放路径,此路径为服务器上的绝对路径
        String imageDIR =request.getSession().getServletContext().getRealPath("/");
        exporter.setParameter(JRHtmlExporterParameter.IMAGES_DIR_NAME, imageDIR);

        //设置图片请求URI
        String imageURI = request.getContextPath() + "/";
        exporter.setParameter(JRHtmlExporterParameter.IMAGES_URI, imageURI);

        //设置导出图片到图片存放路径
        exporter.setParameter(JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN, Boolean.TRUE);
        exporter.setParameter(JRHtmlExporterParameter.IS_OUTPUT_IMAGES_TO_DIR, Boolean.TRUE); 
        exporter.exportReport();

        out.flush();

    }
    public static void showHtml(String defaultFilename, String reportfile,
            HttpServletRequest request, HttpServletResponse response, Map parameters,
            Connection conn) throws JRException, IOException {


        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html");

        JRAbstractExporter exporter = getJRExporter(DocType.HTML);

        JasperPrint jasperPrint = JasperFillManager.fillReport(reportfile,
                parameters, conn);
        request.getSession().setAttribute(
                ImageServlet.DEFAULT_JASPER_PRINT_SESSION_ATTRIBUTE,
                jasperPrint);

        PrintWriter out = response.getWriter();

        exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
        exporter.setParameter(JRExporterParameter.OUTPUT_WRITER, out);
        exporter.setParameter(
        JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN,
        Boolean.FALSE);
        //设置图片文件存放路径,此路径为服务器上的绝对路径
        String imageDIR =request.getSession().getServletContext().getRealPath("/");
        exporter.setParameter(JRHtmlExporterParameter.IMAGES_DIR_NAME, imageDIR);

        //设置图片请求URI
        String imageURI = request.getContextPath() + "/";
        exporter.setParameter(JRHtmlExporterParameter.IMAGES_URI, imageURI);

        //设置导出图片到图片存放路径
        exporter.setParameter(JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN, Boolean.TRUE);
        exporter.setParameter(JRHtmlExporterParameter.IS_OUTPUT_IMAGES_TO_DIR, Boolean.TRUE); 
        exporter.exportReport();
        out.flush();

    }
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static void showPdf(String defaultFilename, String reportfile,
            HttpServletRequest request, HttpServletResponse response, Map parameters,
            JRDataSource conn) throws JRException, IOException {


        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html");
        response.setContentType("application/pdf");

        JRAbstractExporter exporter = getJRExporter(DocType.PDF);

        JasperPrint jasperPrint = JasperFillManager.fillReport(reportfile,
                parameters, conn);
        request.getSession().setAttribute(
                ImageServlet.DEFAULT_JASPER_PRINT_SESSION_ATTRIBUTE,
                jasperPrint);

        OutputStream out = response.getOutputStream();

        exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
        exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, out);
        exporter.exportReport();
        out.flush();

    }
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static void showPdf(String defaultFilename, String reportfile,
            HttpServletRequest request, HttpServletResponse response, Map parameters,
            Connection conn) throws JRException, IOException {


        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html");
        response.setContentType("application/pdf");

        JRAbstractExporter exporter = getJRExporter(DocType.PDF);

        JasperPrint jasperPrint = JasperFillManager.fillReport(reportfile,
                parameters, conn);
        request.getSession().setAttribute(
                ImageServlet.DEFAULT_JASPER_PRINT_SESSION_ATTRIBUTE,
                jasperPrint);

        OutputStream out = response.getOutputStream();

        exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
        exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, out);
        exporter.exportReport();
        out.flush();

    }

}

显示常用设置

1.内容换行
jasperReports+ireport+java运用_第40张图片

2.区块区域之间导出存在空白,或空白分页,禁用分页

3.让内容浮动显示,自动填充无数据的空白区域
jasperReports+ireport+java运用_第41张图片

4.饼状图百分比显示小数为控制
方案一:
百分比由自己在javaben中计算由String类型表示例如“12.53%”;当作其他结果参数一样传递在饼图设置里赋值到label expression:
jasperReports+ireport+java运用_第42张图片

方案二:
首先建立数据源求和
jasperReports+ireport+java运用_第43张图片

赋值到label expression:

String.valueOf(new BigDecimal($F{number}.doubleValue()/$V{variable1}.doubleValue()*100).setScale(2,BigDecimal.ROUND_HALF_UP))+'%'

jasperReports+ireport+java运用_第44张图片

你可能感兴趣的:(工作笔记)