package com.naxsu.report;
import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.export.JRHtmlExporter;
import
net.sf.jasperreports.engine.export.JRHtmlExporterParameter;
import net.sf.jasperreports.engine.export.JRPdfExporter;
import net.sf.jasperreports.engine.util.JRLoader;
/**
* JasperReports生成报表简单应用
*/
public class ReportTest {
/**
* 编译报表
*/
public static void
compiler(String sourceFileName, String destFileName) {
try {
JasperCompileManager.compileReportToFile(sourceFileName,
destFileName);
} catch (JRException
e) {
e.printStackTrace();
}
}
/**
* 填充报表
*/
public static void fill(String
sourceFileName, String destFileName) {
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/report", "root", "123");
JasperFillManager.fillReportToFile(sourceFileName,
destFileName,null, conn);
} catch (JRException
e) {
e.printStackTrace();
} catch
(ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException
e) {
e.printStackTrace();
}finally{
if(conn != null) {
try {
conn.close();
} catch (SQLException
e) {
e.printStackTrace();
}
}
}
}
/**
* 导出HTML格式报表
*/
public static void
exportToHTML(String sourceFileName, String destFileName) {
try {
JasperPrint jp = (JasperPrint)
JRLoader.loadObject(new File(
sourceFileName));
JRHtmlExporter export = new
JRHtmlExporter();
export.setParameter(JRExporterParameter.JASPER_PRINT, jp);
export.setParameter(JRExporterParameter.OUTPUT_FILE_NAME,
destFileName);
export.setParameter(
JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN,
Boolean.FALSE);
export.exportReport();
} catch (JRException
e) {
e.printStackTrace();
}
}
/**
* 导出PDF格式报表
*/
public static void
exportToPDF(String sourceFileName, String destFileName) {
try {
JasperPrint jp = (JasperPrint)
JRLoader.loadObject(new File(
sourceFileName));
JRPdfExporter export = new
JRPdfExporter();
export.setParameter(JRExporterParameter.JASPER_PRINT, jp);
export.setParameter(JRExporterParameter.OUTPUT_FILE_NAME,
destFileName);
export.setParameter(
JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN,
Boolean.FALSE);
export.exportReport();
} catch (JRException
e) {
e.printStackTrace();
}
}
public static void main(String[]
args) {
String jrxmlName = "E:\\JasperReports_iReport\\report1.jrxml";
String jasperFileName = "E:\\JasperReports_iReport\\report1.jasper";
String jrprintFileName = "E:\\JasperReports_iReport\\report1.jrprint";
String htmlFileName = "E:\\JasperReports_iReport\\report1.pdf";
ReportTest.compiler(jrxmlName,
jasperFileName);
ReportTest.fill(jasperFileName,
jrprintFileName);
ReportTest.exportToPDF(jrprintFileName,
htmlFileName);
}
}
|