1)用ireport创建完成jrxml文件后,到ireport的安装目录找到相应的jasper文件,然后放到项目的一个目录中。(由于让程序每次都编译jrxml很浪费时间,再说模板也不容易改变,建议只编译一次就OK)
2)使用代码如下
Session session = HibernateUtil.currentSession();
Connection con = session.connection(); //得到链接
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select * from applications_list where app_id='" +appId+"'"); //用数据集传入带参数的SQL语句
System.out.println("select * from applications_list where appl_list_id='" +appId+"'");
String appPath = request.getSession().getServletContext().getRealPath("/"); //得到以便于好的jasper文件
if (appPath.lastIndexOf("//") != appPath.length() - 1)appPath += "//";
String reportFileName = appPath+ "jasper//untitled_report_1.jasper";
Map parameters = new HashMap();
parameters.put("Title", "设备申请列表");//注意可以有很多个参数
JasperPrint jasperPrint = JasperFillManager.fillReport(reportFileName, parameters, new JRResultSetDataSource(rs));
JRRtfExporter exporter = null;
exporter = new JRRtfExporter();
response.setContentType("text/html; charset=UTF-8");
response.setContentType("application/msword");
String applicatiosname = ToUTF8.toUtf8String("设备申请单"); //处理下载后文件名中文问题
response.setHeader("Content-disposition","attachment;filename="+applicatiosname+".doc");
exporter.setParameter(JRExporterParameter.CHARACTER_ENCODING, "UTF-8");
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, response.getOutputStream());
exporter.exportReport();