public String iReport(){
Map parameters = new HashMap();
HouseAndHouse info = this.getModel();
// parameters.put("NAME", "ff");
Connection conn = null;
ServletContext context = this.getSession().getServletContext();
String path = context.getRealPath("/") + "WEB-INF/page/houseAndHouse/report1.jasper";
try {
Class.forName("com.mysql.jdbc.Driver");
conn
=DriverManager.getConnection("jdbc:mysql://192.168.1.98:3306/framework?useUnicode=true&characterEncoding=utf8","framework","password");
File reportFile = new File(path);
File sourceFile = new File(reportFile.getPath());
JasperReport jasperReport = (JasperReport)JRLoader.loadObject(sourceFile);
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters,conn);
File destFile = new File(context.getRealPath("/") + jasperPrint.getName() + ".html");
String destFileName = destFile.toString();
JRHtmlExporter exporter = new JRHtmlExporter();
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, destFileName);
exporter.setParameter(JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN, Boolean.FALSE);
exporter.setParameter(JRHtmlExporterParameter.BETWEEN_PAGES_HTML, "");
exporter.setParameter(JRExporterParameter.CHARACTER_ENCODING, "UTF-8"); //關鍵是此句
exporter.exportReport();
fileName = jasperPrint.getName() + ".html";
System.out.println(jasperPrint.getName());
conn.close();
}catch (Exception e) {
e.printStackTrace();
}
this.getRequest().setAttribute("fileName", fileName);
return "ireport";
}
這個方法是導出html頁面的一個方法
public void ireportPDF(){
Map parameters = new HashMap();
HouseAndHouse info = this.getModel();
parameters.put("name", info.getName());
parameters.put("workUnit",info.getWorkUnit());
Connection conn = null;
ServletContext context = this.getSession().getServletContext();
String path = context.getRealPath("/") + "WEB-INF/page/houseAndHouse/report1.jasper";
try {
Class.forName("com.mysql.jdbc.Driver");
conn
=DriverManager.getConnection("jdbc:mysql://192.168.1.98:3306/framework?useUnicode=true&characterEncoding=utf8","framework","password");
File reportFile = new File(path);
System.out.println(reportFile.getPath()+"======");
byte[] bytes = JasperRunManager.runReportToPdf(reportFile.getPath(), parameters, conn);
// byte[] bytes = JasperRunManager.runReportToHtmlFile(reportFile.getPath(), parameters, conn);
this.getResponse().setContentType("application/pdf");
this.getResponse().setContentLength(bytes.length);
ServletOutputStream ouputStream = this.getResponse().getOutputStream();
ouputStream.write(bytes, 0, bytes.length);
ouputStream.flush();
ouputStream.close();
}catch (Exception e) {
e.printStackTrace();
}
}
這個方法是導出pdf的一個方法。
到官方下載了ireport3.6的版本,其實ireport編譯用到的包是jasperreports-3.5.2.jar這個版本的,所以在我們的項目中要有這個包才能解析,也就是說ireport裏的包和jasperreports-3.5.2.jar這個包的版本要一樣才能解析成功,不然會報錯。解析不了我們繪製好的test.jasper的報表文件。
在eclipse項目中,我只添加了如下四個包