我有两种方法可以使用primefaces从jasper报告中导出pdf和excel。导出pdf方法非常有效。但是导出excel导出.xlxs尽管excel文件中有html代码,但没有任何必需的数据。代码如下。
ChatListBean.java
public void printExcel(){
String reportPath = JsfUtil.getAbsolutePath("/resources/reports/chat.jasper");
String subReportPath = JsfUtil.getAbsolutePath("/resources/reports");
String realPath = JsfUtil.getAbsolutePath("");
Map<String, Object> params = new HashMap<String, Object>();
params.put("realPath", realPath);
params.put("SUBREPORT_DIR", subReportPath);
// params.put("location", selectedLocation.getName());
JRBeanCollectionDataSource beanCollectionDataSource = new JRBeanCollectionDataSource(findChats);
try {
JasperReportUtil.toEXCEL(beanCollectionDataSource, reportPath, params, "Chat_History");
} catch (Exception ex) {
Logger.getLogger(ChatListBean.class.getName()).log(Level.SEVERE, null, ex);
}
}
JasperReportUtil.java
public static void toEXCEL(JRBeanCollectionDataSource beanCollectionDataSource, String reportPath, Map<String, Object> params, String reportName) throws Exception{
JasperPrint jasperPrint = JasperFillManager.fillReport(reportPath, params, beanCollectionDataSource);
HttpServletResponse httpServletResponse = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
httpServletResponse.addHeader("Content-disposition", "attachment; filename=" + reportName + ".xlsx");
JRXlsExporter xlsExporter = new JRXlsExporter();
xlsExporter.setExporterInput(new SimpleExporterInput(jasperPrint));
xlsExporter.setExporterOutput(new SimpleOutputStreamExporterOutput(reportName));
xlsExporter.exportReport();
FacesContext.getCurrentInstance().responseComplete();
}
这是导出的Excel文件
<groupId>net.sf.jasperreports</groupId>
<artifactId>jasperreports</artifactId>
<version>6.5.1</version>
和
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.16</version>
答案 0 :(得分:0)
我用 xlsExporter.setExporterOutput 方法做错了,工作代码是
public static void toEXCEL(JRBeanCollectionDataSource beanCollectionDataSource, String reportPath, Map<String, Object> params, String reportName) throws Exception{
JasperPrint jasperPrint = JasperFillManager.fillReport(reportPath, params, beanCollectionDataSource);
HttpServletResponse httpServletResponse = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
httpServletResponse.addHeader("Content-disposition", "attachment; filename=" + reportName + ".xlsx");
ServletOutputStream servletOutputStream = httpServletResponse.getOutputStream();
JRXlsExporter xlsExporter = new JRXlsExporter();
xlsExporter.setExporterInput(new SimpleExporterInput(jasperPrint));
xlsExporter.setExporterOutput(new SimpleOutputStreamExporterOutput(servletOutputStream));
xlsExporter.exportReport();
FacesContext.getCurrentInstance().responseComplete();
}