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

iReport 與 JasperReport 開發實戰(一):環境建置、資料源設定與首份報表

     編輯:Java 相關知識

工具簡介與版本對應

  • JasperReport:報表引擎庫,支援 PDF/HTML/XLS/CSV/RTF/XML 輸出,資料來源含 JDBC、JavaBean、XML、CSV 等
  • iReport:視覺化設計工具,產出 .jrxml(XML 定義)→ 編譯為 .jasper(二進位)供引擎執行
  • 本文版本:iReport 0.4.1 / JasperReport 0.6.5(歷史版本,現已更新至 6.x/7.x,概念相通)

執行環境需求

  • JDK 1.2.2+(現代建議 JDK 8/11/17/21 LTS)
  • 解壓 iReport,雙擊 iReport.bat 啟動(Linux/Mac 用 iReport.sh)

建立首份報表步驟

  1. 新建報表:File → New Document 或工具列圖示
  2. 報表屬性:
    • Report Name:命名(如 EmployeeReport)
    • Page size:A4、Letter 等
    • i18n → XML Encoding:建議 UTF-8(舊版預設),中文環境可改 GB2312/Big5,但 UTF-8 通用性最佳
  3. 設定資料源:DataSource → Connections/DataSources → New
    • 類型:JDBC
    • 名稱:自訂(如 MySQL_HR)
    • JDBC Driver:com.mysql.cj.jdbc.Driver (MySQL 8+) 或 com.microsoft.sqlserver.jdbc.SQLServerDriver
    • JDBC URL:jdbc:mysql://localhost:3306/hrdb?useSSL=false&serverTimezone=UTC
    • 使用者/密碼:資料庫帳號
    • 點 Wizard 更新 URL → Test 驗證連線
  4. 設計查詢:DataSource → Report query
    • 輸入 SQL:SELECT emp_id, emp_name, dept, salary FROM employee
    • 取消 Automatically Retrieve Fields → Read Fields 讀取欄位清單
  5. 版面配置:View → Report Fields 拖入 Detail 區,或手工繪製文字欄位設定 $F{emp_name} 等運算式
  6. 加入標題:Title 區放置靜態文字「員工薪資表」
  7. 編譯與預覽:
    • 工具列「編譯」產生 .jasper
    • 點選「執行動態報表」(資料庫圖示)填充資料預覽
    • 或 Build 選單匯出 PDF/XLS/HTML

中文亂碼預防(重點)

  1. 下載 itext-asian-5.2.0.jar (Maven: com.itextpdf:itext-asian) 放入 classpath
  2. 報表屬性 PDF Font Name = STSong-Light
  3. PDF Encoding = UniGB-UCS2-H (簡體) / UniCNS-UCS2-H (繁體)
  4. PDF Embedded = true

常見入門錯誤

現象原因修正
預覽僅顯示標題,資料欄位為 null點擊「靜態預覽」而非「動態填充」使用資料庫圖示按鈕
編譯報 NoClassDefFoundError缺少 JasperReport 核心 JARMaven 引入 net.sf.jasperreports:jasperreports
匯出 PDF 中文方塊未設亞洲字體依上節設定字體與編碼
欄位型別錯誤導致編譯失敗Field Class 與資料庫不符修正為 java.lang.String/Integer/Date 等

程式碼整合範例

// Spring Boot Controller
@GetMapping("/report/employee.pdf")
public void exportEmployeeReport(HttpServletResponse response) throws Exception {
    InputStream jasperStream = getClass().getResourceAsStream("/reports/EmployeeReport.jasper");
    JasperReport jasperReport = (JasperReport) JRLoader.loadObject(jasperStream);

    Map<String, Object> params = new HashMap<>();
    params.put("title", "員工薪資表");

    JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, params, dataSource.getConnection());

    response.setContentType("application/pdf");
    response.setHeader("Content-Disposition", "attachment; filename=employee.pdf");
    JasperExportManager.exportReportToPdfStream(jasperPrint, response.getOutputStream());
}

總結

掌握「新建 → 資料源 → 查詢 → 版面 → 編譯 → 預覽」六步驟,並解決中文字體、欄位型別、預覽模式三大新手坑,即可快速上手 JasperReport 生態。建議直接使用最新版 JasperReport Library (7.x+) 與 Jaspersoft Studio (Eclipse-based 設計工具),獲得更好支援。

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