Home

hogen

Follow Excellence. Success will chase you.

Home About Github Email

Jasperreport 报表开发

绝大多数 WEB 项目都会有报表开发的模块,对于客户来说可以直观了解各项数据的产生和使用情况,笔者最近接触的小贷系统也有报表打印模块,也参与到了报表开发中,这也是我第一次接触报表开发,这篇文章算是对完成之后的一番总结吧!

笔者接触的报表开发使用的工具是 ireport,iReport 是一个能够创建复杂报表的开源项目,使用纯 Java 编写,拥有非常丰富的图形界面,并且它能调用 JasperReports 库应用于任何一种 java 应用程序,JasperReports 支持 PDF、HTML、XLS、CSV 和 XML 文件输出格式,是开源报表工具中比较常用的。

这里我就用一个 web projects 来演示如何打印一张报表,包括 PDF、excel 格式的

工具准备

  • myeclipse
  • 数据库
  • ireport5.6

新建 Web Project,目录结构及所需要的jar包如下

项目结构

所需jar包

具体可视情况而定,如果只要打印 pdf 可以去掉一些 jar 包的,这里我因为excel、htlml、ttf 等各种格式都打印了,所以全部加上吧;另外版本一定要对应:我用的是ireport5.6,jasperreports-5.6.0.jar 、 jasper-compiler-jdt-5.5.15.jar 、iText-2.1.7.js2.jar 也要是高版本,否则会报错,空指针之类的。

画报表,保存到 webroot/report/jrxml 路径下

报表的操作很简单,只要拖动、设置各种控件,就能迅速得到自己想要的报表,而通过数据的输入可以得到各种图表,这里就不详述 ireport 工具的操作使用了,我画的报表界面如下:

报表

设置报表编译路径,保存到 webroot/report/jasper 路径下

报表编译路径

从页面跳转到 servlet

为了简便,我就在 index.jsp 页面写了两超链接,分别打印 PDF 和 EXCEL 格式的报表,如下:

<body>
   <a href="TestReport?type=pdf">PDF导出</a>
   <br/>
   <a href="TestReport?type=excel">excel导出</a>
</body>

JDBC 数据库连接(这里就罗列关键代码)

连接数据库

public static Connection getConnection() {
    Connection connection = null;
    try {
        Class.forName("com.mysql.jdbc.Driver");
        connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/loans", "root", "root");
    } catch (Exception e) {
         e.printStackTrace();
    }
    return connection;
}

查询数据库表数据

public static List selectAll(String sql){
    ResultSet rs = null;
    Statement statement = null;
    Connection conn = null;
    List dataList = new ArrayList();
    try {
        conn = getConnection();
        statement = conn.createStatement();
        rs = statement.executeQuery(sql);
        MakeLoanDetail makeLoanDetail = null;
        while (rs.next()){
            makeLoanDetail = new MakeLoanDetail();
            //把值 set 到 javabean 对象
            makeLoanDetail.setCustName(rs.getString(1));
            makeLoanDetail.setCustIdNo(rs.getString(2));
            makeLoanDetail.setBrdName(rs.getString(3));
            makeLoanDetail.setApprAmt(rs.getDouble(4));
            makeLoanDetail.setApprTerm(rs.getInt(5));
            makeLoanDetail.setActvSysDt(rs.getDate(6));
            makeLoanDetail.setActvUserId(rs.getString(7));
            //最后把对象添加到 list 集合中去,dataList 将最终传到报表中去
            dataList.add(makeLoanDetail);
        }
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }finally {
       //这里关闭 rs,statement,conn 资源
    }
    return dataList;
}

servlet 逻辑处理

public class TestReport extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Map parameterMap = new HashMap();
        parameterMap.put("PRINT_DATE", new Date());//此处的键值对应报表 parameter 中的字段
        String reportMode = "";
        String type = request.getParameter("type");
        if (type.equals("pdf")) {
            reportMode = "pdf";
        }else if (type.equals("excel")) {
            reportMode = "excel";
        }
        String reportName = "WhLoan_Detail_Report";//报表名字,打印出来的报表名
        String reportId = "WhLoan_Detail_Report";//报表Id,对应于webroot/report/jrxml 你保存的报表名
        String sql = "SELECT CI.CUST_NAME,CI.cust_id_no,LB.BRD_NAME,APPR_AMT,APPR_TERM,ACTV_SYS_DT,ACTV_USER_ID"
                   +" FROM loan,cust_info CI,LOAN_BRD LB"//注意 FROM 前要有空格
                   +" WHERE loan.CUST_ID_CTRY = CI.CUST_ID_CTRY"//空格
                   +" AND LOAN.CUST_ID_NO = CI.CUST_ID_NO"//空格
                   +" AND LOAN.CUST_ID_TYPE = CI.CUST_ID_TYPE"
                   +" AND LOAN.LOAN_BRD = LB.BRD_ID";
        try {
            List dataList = SqlHelper.selectAll(sql);
            ReportExporter.exportReport(request, response, reportId, reportMode, parameterMap, dataList, reportName);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}

考虑到各大浏览器的兼容性,最好将 reportName 用英文而不是中文,sql 语句查询出来的字段要一一对应 javaBean 中成员变量

ReportExporter 类

ReportExporter 封装了导出 pdf,excel,html等全部格式的方法,直接调用即可

public class ReportExporter {
    /**
     * 获取打印报表
     */
    public static void exportReport(HttpServletRequest request, HttpServletResponse response, String reportId,
            String exportMode, Map parameterMap, List dataList, String downloadFileName) throws Exception {
        Connection connection = null;
        try {
            if (dataList == null) {
                connection = SqlHelper.getConnection();
            }
            ServletContext servletContext = request.getSession().getServletContext();
            File jasperFile = new File(servletContext.getRealPath("/report/jasper/" + reportId + ".jasper"));
            if (!jasperFile.exists())
                throw new IOException("Report file can't be found");

            if (parameterMap == null)
                parameterMap = new HashMap();
            //ireport3.0用这个
            // JasperReport jasperReport = (JasperReport)JRLoader.loadObject(jasperFile.getPath());
            JasperReport jasperReport = (JasperReport) JRLoader.loadObject(jasperFile);
            JasperPrint jasperPrint = null;
            if (dataList == null) {
                jasperPrint = JasperFillManager.fillReport(jasperReport, parameterMap, connection);
            } else {
                JRDataSource source = new JRBeanCollectionDataSource(dataList);
                jasperPrint = JasperFillManager.fillReport(jasperReport, parameterMap, source);
            }

            if (request.getHeader("User-Agent").toLowerCase().indexOf("firefox") > 0)
                downloadFileName = new String(downloadFileName.getBytes("UTF-8"), "ISO8859-1");// firefox浏览器
            else if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0)
                downloadFileName = new String(downloadFileName.getBytes("gb2312"), "ISO8859-1");// IE浏览器

            if (ReportExportMode.EXP_PDF_MODE.equalsIgnoreCase(exportMode)) {
                exportPdf(response, jasperPrint, downloadFileName);
            } else if (ReportExportMode.EXP_EXCEL_MODE.equalsIgnoreCase(exportMode)) {
                exportExcel(response, jasperPrint, downloadFileName);
            } else if ("word".equals(exportMode)) {
                exportWord(response, jasperPrint, downloadFileName);
            } else if ("rtf".equals(exportMode)) {
                exportRTF(response, jasperPrint, downloadFileName);
            } else if ("html".equals(exportMode)) {
                exportHtml(response, jasperPrint, downloadFileName);
            }
        } finally {
            if (dataList == null && connection != null)
                try {
                    connection.close();
                } catch (SQLException e) {
                }
        }
    }

    /**
     * pdf导出
     */
    private static void exportPdf(HttpServletResponse response, JasperPrint jasperPrint, String downloadFileName)
            throws JRException, IOException {
        ServletOutputStream ouputStream = response.getOutputStream();

        try {
            JRPdfExporter exporter = new JRPdfExporter();
            exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
            exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, ouputStream);

            response.setContentType("application/pdf;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + downloadFileName + ".pdf");
            exporter.exportReport();
            ouputStream.flush();
        } finally {
            try {
                ouputStream.close();
            } catch (Exception e) {
            }
        }
    }

    /**
     * excel导出
     */
    private static void exportExcel(HttpServletResponse response, JasperPrint jasperPrint, String downloadFileName)
            throws JRException, IOException {
        ServletOutputStream ouputStream = response.getOutputStream();

        try {
            JRXlsExporter exporter = new JRXlsExporter();
            exporter.setParameter(JRXlsExporterParameter.JASPER_PRINT, jasperPrint);
            exporter.setParameter(JRXlsExporterParameter.OUTPUT_STREAM, ouputStream);
            response.setContentType("application/vnd_ms-excel;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + downloadFileName + ".xls");
            exporter.exportReport();
            ouputStream.flush();
        } finally {
            try {
                ouputStream.close();
            } catch (Exception e) {
            }
        }
    }

    /**
     * 导出word
     */
    private static void exportWord(HttpServletResponse response, JasperPrint jasperPrint, String downloadFileName)
            throws JRException, IOException {
        ServletOutputStream ouputStream = response.getOutputStream();

        try {
            JRExporter exporter = new JRRtfExporter();
            exporter.setParameter(JRXlsExporterParameter.JASPER_PRINT, jasperPrint);
            exporter.setParameter(JRXlsExporterParameter.OUTPUT_STREAM, ouputStream);

            response.setContentType("application/msword;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + downloadFileName + ".doc");
            exporter.exportReport();
            ouputStream.flush();
        } finally {
            try {
                ouputStream.close();
            } catch (Exception e) {
            }
        }
    }

    /**
     * 导出RTF
     */
    private static void exportRTF(HttpServletResponse response, JasperPrint jasperPrint, String downloadFileName)
            throws JRException, IOException {
        ServletOutputStream ouputStream = response.getOutputStream();

        try {
            JRExporter exporter = new JRRtfExporter();
            exporter.setParameter(JRXlsExporterParameter.JASPER_PRINT, jasperPrint);
            exporter.setParameter(JRXlsExporterParameter.OUTPUT_STREAM, ouputStream);

            response.setContentType("application/rtf;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + downloadFileName + ".rtf");
            exporter.exportReport();
            ouputStream.flush();
        } finally {
            try {
                ouputStream.close();
            } catch (Exception e) {
            }
        }
    }

    /**
     * 导出html
     */
    private static void exportHtml(HttpServletResponse response, JasperPrint jasperPrint, String downloadFileName)
            throws JRException, IOException {
        ServletOutputStream ouputStream = response.getOutputStream();

        try {
            JRHtmlExporter exporter = new JRHtmlExporter();
            exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
            exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, ouputStream);
            exporter.setParameter(JRExporterParameter.CHARACTER_ENCODING, "UTF-8");
            exporter.setParameter(JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN, Boolean.FALSE);
            response.setContentType("text/html;charset=utf-8");
            exporter.exportReport();
            ouputStream.flush();
        } finally {
            try {
                ouputStream.close();
            } catch (Exception e) {
            }
        }
    }
}

ReportExportMode 类

public class ReportExportMode {

    public static String EXP_PDF_MODE="PDF";
    public static String EXP_EXCEL_MODE="EXCEL";
    public static boolean isPDF(String mode){
        return EXP_PDF_MODE.equals(mode);
    }
    public static boolean isEXCEL(String mode){
        return EXP_EXCEL_MODE.equals(mode);
    }
}

运行程序

点击 PDF 导出 和 EXCEL 导出

pdf 导出

excel导出


hogen

2017-05-06
Home About Github Email