首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

JasperReports 實戰:JSP 中導出 PDF、Excel、HTML 完整教程

     編輯:Java 相關知識

JasperReports 是 Java 生態最成熟的報表引擎,配合 iReport 可視化設計工具,能快速實現複雜報表的 PDF、Excel、HTML 多格式導出。本文基於 JasperReports 3.5.x,詳述環境搭建、中文支持、JSP 導出實現、常見坑點解決方案。

一、環境準備與依賴管理

核心 JAR 包清單

  • jasperreports-3.5.0.jar — 核心引擎
  • iText-2.1.5.jar + iTextAsian.jar — PDF 中文支持(關鍵)
  • poi-3.2-FINAL.jar — Excel 導出支持
  • commons-beanutils-1.8.0.jar、commons-collections-3.2.1.jar、commons-digester-2.0.jar、commons-logging.jar — Apache 通用依賴
  • com-jaspersoft-ireport.jar — iReport 整合包
  • 資料庫驅動(如 mysql-connector-java-5.0.3-bin.jar)

版本兼容提示:JasperReports 3.x 需 iText 2.1.x,JasperReports 6.x+ 升級為 iText 5/7,包結構變化大,升級時請查閱官方遷移指南。

二、iReport 設計器中文配置(關鍵步驟)

  1. 安裝 iReport 3.5.0,啟動後 Tools → Options → Classpath 添加 iText-2.1.5.jar、iTextAsian.jar
  2. 報表屬性設置:Format → Fonts 統一設置默認字體:
    • Font name: 宋體(或微軟雅黑)
    • PDF Font name: STSong-Light
    • PDF Encoding: UniGB-UCS2-H (簡體) / UniCNS-UCS2-H (繁體)
    • PDF Embedded: ☑ 勾選
  3. 保存報表自動生成 .jrxml 與編譯後的 .jasper 檔案

三、JSP 多格式導出核心代碼

<%@ page contentType="text/html;charset=UTF-8" import="java.sql.*,java.io.*,net.sf.jasperreports.engine.*,net.sf.jasperreports.engine.export.*" %>
<%
    // 1. 獲取報表模板路徑
    String jasperDir = application.getRealPath("/report/jasper");
    String reportName = "employee"; // employee.jasper
    File jasperFile = new File(jasperDir, reportName + ".jasper");

    // 2. 資料庫連接
    Connection conn = DriverManager.getConnection(
        "jdbc:mysql://localhost:3306/wanrue", "root", "xwrwc");

    // 3. 根據請求參數決定導出格式
    String reportType = request.getParameter("reportType"); // pdf / xls / html
    ServletOutputStream out = response.getOutputStream();

    if ("pdf".equalsIgnoreCase(reportType)) {
        // === PDF 導出:一行代碼直達 ===
        byte[] bytes = JasperRunManager.runReportToPdf(jasperFile.getPath(), null, conn);
        response.setContentType("application/pdf");
        response.setContentLength(bytes.length);
        out.write(bytes);
        
    } else if ("xls".equalsIgnoreCase(reportType)) {
        // === Excel 導出:JRXlsExporter ===
        JasperPrint jasperPrint = JasperFillManager.fillReport(jasperFile.getPath(), null, conn);
        JRXlsExporter exporter = new JRXlsExporter();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        
        exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
        exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, baos);
        exporter.setParameter(JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, Boolean.TRUE);
        exporter.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET, Boolean.FALSE);
        exporter.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND, Boolean.FALSE);
        exporter.exportReport();
        
        byte[] bytes = baos.toByteArray();
        response.setContentType("application/vnd.ms-excel");
        response.setContentLength(bytes.length);
        out.write(bytes);
        
    } else {
        // === HTML 導出:JRHtmlExporter ===
        JasperPrint jasperPrint = JasperFillManager.fillReport(jasperFile.getPath(), null, conn);
        JRHtmlExporter exporter = new JRHtmlExporter();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        
        exporter.setParameter(JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN, Boolean.FALSE);
        exporter.setParameter(JRHtmlExporterParameter.JASPER_PRINT, jasperPrint);
        exporter.setParameter(JRHtmlExporterParameter.CHARACTER_ENCODING, "UTF-8");
        exporter.setParameter(JRHtmlExporterParameter.OUTPUT_STREAM, baos);
        exporter.exportReport();
        
        byte[] bytes = baos.toByteArray();
        response.setContentType("text/html;charset=UTF-8");
        response.setContentLength(bytes.length);
        out.write(bytes);
    }
    
    out.flush();
    out.close();
    conn.close();
%>

關鍵 API 對比

格式核心類特點
PDFJasperRunManager.runReportToPdf()填充+導出一步完成,效能最佳,適合直接下載
ExcelJasperFillManager.fillReport() + JRXlsExporter需先生成 JasperPrint,支援多 Sheet、去空行等細粒度控制
HTMLJasperFillManager.fillReport() + JRHtmlExporter適合網頁預覽,需注意編碼與圖片資源處理

四、中文亂碼三大經典問題與解決方案

現象原因解決方案
PDF/Excel 預覽拋出 Could not load font: STSong-Light缺少 iTextAsian.jar(亞洲語言包)將 iTextAsian.jar 放入類路徑(WEB-INF/lib 或 iReport lib 目錄)
PDF/Excel 無報錯但中文顯示空白報表元素字體屬性設置錯誤iReport 中每個文本框/靜態文本設置:Font=宋體、PDF Font=STSong-Light、PDF Encoding=UniGB-UCS2-H、Embedded=真
HTML 導出中文亂碼響應編碼未統一JSP 頁面指令 charset=UTF-8;Servlet 中 response.setContentType("text/html;charset=UTF-8");若項目有統一編碼過濾器,以過濾器為準

五、JRXML 編碼內幕

iReport 生成的 .jrxml 頭部聲明:<?xml version="1.0" encoding="UTF-8"?>。報表內的中文均以 UTF-8 存儲。項目全鏈路建議統一 UTF-8:

  • 資料庫連接 URL 加 characterEncoding=UTF-8
  • Tomcat server.xml URIEncoding="UTF-8"
  • JSP/HTML 頁面 charset=UTF-8
  • JVM 啟動參數 -Dfile.encoding=UTF-8

六、生產環境優化建議

  1. 連接池:JSP 直連資料庫僅供測試,生產必須用 DataSource (DBCP/HikariCP)
  2. 報表緩存:.jasper 檔案應啟動時預加載緩存,避免重複磁盤 IO
  3. JasperFillManager.fillReport() 耗時長,建議異步生成或佇列處理
  4. 大數據量分頁:使用 JRVirtualizer 避免 OOM
  5. 字體註冊:Spring Boot 專案可通過 FontUtil.setFontMap() 統一註冊字體,省去 iReport 逐個設置

總結:JasperReports + iReport 是 Java 報表經典組合。掌握「模板設計→中文配置→多格式導出 API→編碼統一」四步曲,能高效交付專業級報表功能。現代項目建議考慮 JasperReports 6.x+ 或遷移至 Spring Boot + JasperReports Starter 簡化配置。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved