I have a Jasper Report that generates an Excel file and outputs as a byte[], I want the file to appear as a download in the browser but at the moment it just prints the raw code to the browser.
The relevant part of the code is below, this is initiated from an AJAX request (the page has already been loaded):
JasperReport jasperReport;
JasperPrint jasperPrint;
HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
byte[] excel = null;
FacesContext facesContext = FacesContext.getCurrentInstance();
try {
ArrayList<SwimDataReport> dataList = getData();
if(dataList!=null){
JRBeanCollectionDataSource dataSource = new JRBeanCollectionDataSource(dataList, false);
jasperReport = JasperCompileManager.compileReport(reportFile.getPath());
jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, dataSource);
JRXlsExporter exporter = new JRXlsExporter();
ByteArrayOutputStream xlsReport = new ByteArrayOutputStream();
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, xlsReport);
exporter.exportReport();
excel = xlsReport.toByteArray();
response.reset();
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-disposition", "attachment; filename=\"Export.xls\"");
xlsReport.close();
OutputStream ouputStream = response.getOutputStream();
ouputStream.write(excel);
ouputStream.close();
facesContext.responseComplete();
this.cleanUp();
}else{
return;
}
} catch (JRException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
Any ideas where I am going wrong?
It appears you cannot download a file from an AJAX request, so I have used the h:commandButton to trigger the download instead.