jasperreports是Java語言中比較流行的報表解決方案识腿,以下主要介紹如何運用此技術(shù)渡讼。
jasperreports的依賴包
barbecue-1.5-beta1.jar成箫、barcoder4j-2.1.jar和batik-.jar:用于二維碼和條形碼的生成蹬昌。
commons-.jar:常規(guī)依賴包
iText.jar:中文的依賴包
mysql-connerctor.jar和ojdbc6.jar:jdbc依賴
xml-apis-*.jar:讀取jasperreports配置報表的xml讀取工具包
jasperreports代碼案例
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
/**
*@author:tp
*@create date:2017-10-17
*/
public class JasperReport {
public static Connection getMySqlConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
return DriverManager.getConnection("jdbc:mysql://10.2.8.15:3306/jasperreport", "root", "root");
} catch (SQLException e) {
throw new RuntimeException(e);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
public static Connection getOracleConnection() {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
return DriverManager.getConnection("jdbc:oracle:thin:@10.2.8.5:1521:orcl", "dispatch", "dispatch");
} catch (SQLException e) {
throw new RuntimeException(e);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
public static void oracleExport() throws Exception {
InputStream inputStream = JasperReport.class.getResourceAsStream("../file/collect_new_print.jasper");
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("fid", "TN20102050013");//標(biāo)題參數(shù)
parameters.put("deptId", "1");//標(biāo)題參數(shù)
parameters.put("operman", "測試人員");//標(biāo)題參數(shù)
Connection connection = getOracleConnection();
JasperPrint jasperPrint = JasperFillManager.fillReport(inputStream, parameters, connection);
JasperExportManager.exportReportToPdfFile(jasperPrint, "collect_new_print.pdf");//在當(dāng)前項目地址中生成pdf
}
public static void mySqlExport() throws Exception {
InputStream inputStream = JasperReport.class.getResourceAsStream("../file/report1.jasper");
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("P_title", "管理員列表");//標(biāo)題參數(shù)
Connection connection = getMySqlConnection();
JasperPrint jasperPrint = JasperFillManager.fillReport(inputStream, parameters, connection);
JasperExportManager.exportReportToPdfFile(jasperPrint, "report1.pdf");//在當(dāng)前項目地址中生成pdf
}
public static void main(String[] args) throws Exception {
//mySqlExport();
oracleExport();
}
}
常見問題
問題:配置PDF模板時明刷,中文無法顯示
解決方案:需要定義單元格的格式為:pdfFontName="STSong-Light" pdfEncoding="UniGB-UCS2-H" isPdfEmbedded="true"
問題:ireport無法讀取Oracle數(shù)據(jù)庫
解決方案:需要在軟件增加jdbc依賴,然后工具中classpath配置對應(yīng)的路徑
問題:ireport閃退問題
解決方案:需要配置軟件的JDK路徑本冲,配置文件路徑為:etc/ireport.conf
# default location of JDK/JRE, can be overridden by using --jdkhome <dir> switch
jdkhome=T:\\tool\\jdk\\jdk7\\jdk1.7.0_80