Most of the WEB project will have report development module, can be intuitive understanding of the data to the customer is the production and usage, I recently small contact of the credit system also has a print module, also involved in report development, this is my first time to contact report development, this article is a summary after to finish!

Ireport is an open source project that can create complex reports. It is written in pure Java and has a very rich graphical interface. Moreover, it can call JasperReports library and apply it to any Java application. JasperReports supports PDF, HTML, XLS, CSV and XML file output formats, which are commonly used among open source reporting tools.

I’m going to use a Web Projects to show you how to print a report, including PDF, Excel, all right

Tools to prepare

  • myeclipse
  • The database
  • ireport5.6

Create a Web Project. The directory structure and required JAR packages are as follows

Depending on the situation, if you only print PDF, you can remove some JAR packages. Here, I have printed excel, HTLML, TTF and other formats, so I will add all of them. In addition, the version must correspond to: Jar,jasper – Compiler-JDT -5.5.15.jar, IText-2.1.7.js2. Jar also need higher versions, otherwise it will give an error, null pointer, etc.

Draw a report and save it to the webroot/ Report/JRXML path

The operation of report is very simple. As long as you drag and set various controls, you can quickly get the report you want, and you can get various charts through data input. I will not detail the operation of iReport tool here, and THE report interface I draw is as follows:

Set the report compilation path and save it to the webroot/report/jasper path

Jump from the page to the servlet

For simplicity, I have written two hyperlinks in the index.jsp page to print the report in PDF and EXCEL format respectively, as follows:

<body> <a href="TestReport? </a> <a href="TestReport? </a> </body>Copy the code

JDBC database connection (key code listed here)

Connecting to a Database

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;
}
Copy the code

Query database table data

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(); / / the value set to the javabean object makeLoanDetail setCustName (rs) get string (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)); Add (makeLoanDetail); add(makeLoanDetail); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally {// here close rs,statement,conn resource} return dataList; }Copy the code

Servlet logic processing

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()); // The key value corresponds to the parameter field 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"; // Report name. // Report Id, corresponding to webroot/report/ JRXML you save the report name 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"// Note that FROM must have Spaces +" WHERE loan.CUST_ID_CTRY = CI.CUST_ID_CTRY"// space +" AND loan. CUST_ID_NO = CI.CUST_ID_NO"// space +" 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); }}Copy the code

In consideration of browser compatibility, it is better to write reportName in English rather than Chinese

ReportExporter class

ReportExporter packages PDF, Excel, HTML and other export methods, directly call

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) {
            }
        }
    }
}
Copy the code

ReportExportMode class

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); }}Copy the code

To run the program

Click PDF Export and EXCEL Export

PDF export

Excel export