报表制作流程:
1、在ireport中设计报表模版,并编译
2、//获取报表模版路径
public String getfilePath(String reportName)
{
FacesContext context = FacesContext.getCurrentInstance();
HttpServletRequest request = (HttpServletRequest)context.getExternalContext().getRequest();
String rootPath = request.getRealPath("//");
//定义报表模版路径
String preffix = "/boss/webReport/reports/";
//定义后缀名
String suffix = ".jasper";
//模版绝对路径
String filePath = rootPath+preffix+reportName+suffix;
return filePath;
}
3、// 获得JasperPrint对象;filePath为报表模版路径
public JasperPrint getPrintWithConnection(String filePath, Map parameter, Connection conn) throws JRException
{
JasperReport jasperReport = null;
try
{
jasperReport = (JasperReport) JRLoader.loadObject(filePath);
return JasperFillManager.fillReport(jasperReport, parameter, conn);
}
catch (JRException e)
{
e.printStackTrace();
}
return null;
}
4、//数据库连接
public Connection getconnect() {
Connection connection = null;
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
InputStream dataStream = externalContext
.getResourceAsStream("/WEB-INF/classes/properties.properties");
try {
Properties properties = new Properties();
properties.load(dataStream);
String driverName = properties.getProperty("driverName");
Class.forName(driverName).newInstance();
String url = properties.getProperty("url");
String admin = properties.getProperty("admin");
String password = properties.getProperty("password");
connection = DriverManager.getConnection(url, admin, password);
}
catch (Exception e)
{
e.printStackTrace();
}
return connection;
}
5、//查询报表
public void query(String filePath, Map parameter,Connection con)throws Exception
{
try
{
FacesContext context = FacesContext.getCurrentInstance();
HttpServletResponse response = (HttpServletResponse)context.getExternalContext().getResponse();
JasperPrint jasperPrint = getPrintWithConnection(filePath,parameter, con);
ByteArrayOutputStream oStream = new ByteArrayOutputStream();
JRPdfExporter pdfExporter = new JRPdfExporter();
pdfExporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
pdfExporter.setParameter(JRExporterParameter.OUTPUT_STREAM, oStream);
pdfExporter.exportReport();
byte[] bytes = oStream.toByteArray();
if (bytes != null && bytes.length > 0)
{
response.reset();
response.setContentType("application/pdf");
response.setHeader("Content-disposition","inline;filename=fileName.pdf");
response.setContentLength(bytes.length);
ServletOutputStream ouputStream = response.getOutputStream();
ouputStream.write(bytes, 0, bytes.length);
ouputStream.flush();
ouputStream.close();
context.responseComplete();
}
}
catch(Exception e)
{
e.printStackTrace();
}
}