Boa tarde pessoal!
Estou tendo o seguinte problema ao tentar exportar um relatório para XLS utilizando o Jasper Reports:
Esse erro ocorre na linha:
OutputStream ouputStream = response.getOutputStream();
Eu estou utilizando Struts 1.1 e java 1.4.
Segue abaixo o código da minha aplicação:
Classe ExibirRelatorioAction
public ActionForward executeAction(ActionMapping mapping,
ActionForm form, HttpServletRequest request,
HttpServletResponse response)
throws Exception {
//OutputStream ouputStream = response.getOutputStream();
ActionForward forward = new ActionForward(FORWARD_ERRO);
StreamInfo info = getReport(mapping, form, request, response, forward);
// Caso não se consiga gerar o Relatorio, chamar pagina de Erro
if (info == null) {
return forward;
}
// Caso possa gerar o relatorio, seta-lo no response
String contentType = info.getContentType();
InputStream stream = info.getInputStream();
response.setContentType(contentType);
PrintWriter writer = response.getWriter();
CopiadorDados.copiar(stream, writer);
ActionMessages m = new ActionMessages();
m.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
"mensagem.sucesso.geracao_relatorio"));
addMessages(request, m);
return mapping.findForward(FORWARD_SUCESSO);
}
/**
* Retorna um StreamInfo com as informacoes do relatorio.
* @param mapping Mapping
* @param form Formulario da requisicao
* @param request Request
* @param response Response
* @param forward Pagina de redirecionamento no caso do retorno ser null.
* @return Retorna null caso houver algum erro na geracao do relatório, do
* contrário, retorna um StreamInfo com as informacoes do relatorio
* @throws Exception
*/
protected StreamInfo getReport(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response,
ActionForward forward)
throws Exception {
String tituloRelatorio = request.getParameter("tituloRelatorio");
String tipoRelat = request.getParameter("tipoRelatorio");
UsuarioVO usuarioVO = ControleAcesso.getUsuarioLogado(request);
SASConnectionManager sasConnectionManager = new SASConnectionManager(usuarioVO);
Connection connection = sasConnectionManager.getConnection();
int tipoRelatorio = JasperReportFactory.TIPO_HTML;
HashMap parametros = new HashMap();
parametros.put("libname", sasConnectionManager.getNomeLib());
parametros.put("dataset", getDatasetName(tituloRelatorio));
parametros.put("cenario", request.getSession().getAttribute(Constantes.CHAVE_CENARIO_SELECIONADO));
Enumeration parameterNames = request.getParameterNames();
while (parameterNames.hasMoreElements()) {
String key = (String) parameterNames.nextElement();
parametros.put(key, request.getParameter(key));
}
/* passagem de parametro para integracao do Grafico de Backlog */
Object o = request.getSession().getAttribute("grafico_backlog");
if (o != null ) {
Image imagem = (Image)o;
parametros.put("grafico_backlog", imagem);
}
JasperReportFactory jasperReportFactory = new JasperReportFactory();
if (tituloRelatorio == null)
return null;
if(tipoRelat!=null && !tipoRelat.trim().equals("")){
try{
tipoRelatorio = Integer.parseInt(tipoRelat);
} catch(Exception e){
e.printStackTrace();
}
}
return jasperReportFactory.fabrica(
tituloRelatorio, parametros, tipoRelatorio,
connection, response);
}
Classe JasperReportFactory
public StreamInfo fabrica(String tituloRelatorio, HashMap parametros,
int tipo, Connection fonteDados, HttpServletResponse response) throws JRException, IOException{
String sep = System.getProperty("file.separator");
InputStream inputStream =
RelatorioFactory.class.getResourceAsStream("/"
+ tituloRelatorio + ".jasper");
if (inputStream == null) {
throw new IOException("Relatório Jasper não foi compilado.");
}
JasperPrint print = null;
try {
print = JasperFillManager.fillReport(
inputStream, parametros, fonteDados);
} catch (JRException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
switch (tipo) {
case TIPO_PDF:
return new ByteArrayStreamInfo("application/pdf",
JasperExportManager.exportReportToPdf(print));
case TIPO_XLS:
JRXlsExporter exporter = new JRXlsExporter();
ByteArrayOutputStream xlsReport = new ByteArrayOutputStream();
exporter.setParameter(JExcelApiExporterParameter.JASPER_PRINT, print);
exporter.setParameter(JExcelApiExporterParameter.OUTPUT_STREAM, xlsReport);
exporter.setParameter(JExcelApiExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, Boolean.TRUE);
exporter.setParameter(JExcelApiExporterParameter.IS_WHITE_PAGE_BACKGROUND, Boolean.TRUE);
exporter.setParameter(JExcelApiExporterParameter.IS_ONE_PAGE_PER_SHEET, Boolean.TRUE);
exporter.exportReport();
byte[] bytes = xlsReport.toByteArray();
response.setContentType("application/vnd.ms-excel");
response.setContentLength(bytes.length);
xlsReport.close();
OutputStream ouputStream = response.getOutputStream();
ouputStream.write(bytes, 0, bytes.length);
ouputStream.flush();
ouputStream.close();
return new ByteArrayStreamInfo("application/vnd.ms-excel", bytes);
case TIPO_HTML:
JRHtmlExporter exportador = new JRHtmlExporter();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
exportador.setParameter(JRExporterParameter.JASPER_PRINT, print);
exportador.setParameter(JRExporterParameter.OUTPUT_STREAM, stream);
exportador.setParameter(
JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN,
Boolean.FALSE);
exportador.setParameter(
JRHtmlExporterParameter.IS_OUTPUT_IMAGES_TO_DIR, Boolean.TRUE);
String tempDirName = "jrimg" + Math.random() + "tmp";
File tempDir = new File(System.getProperty("java.io.tmpdir")
+ sep
+ tempDirName);
tempDir.mkdir();
tempDir.deleteOnExit();
exportador.setParameter(
JRHtmlExporterParameter.IMAGES_DIR,
tempDir
);
exportador.setParameter(JRHtmlExporterParameter.IMAGES_URI,
"exibirImagemTemporaria.do?caminho=" + tempDirName + sep);
/* Action do Jasper para exportar imagens
* utilizado pelo Murer para imagens*/
// exportador.setParameter(JRHtmlExporterParameter.IMAGES_URI,
// new StringBuffer("htmlJasperImagerAction?").append(
// ImageServlet.JASPER_PRINT_REQUEST_PARAMETER)
//
// .append("=jasperPrint_image&image=").toString());
//
// request.getSession().setAttribute(
// "jasperPrint_image",
// print);
exportador.exportReport();
return new ByteArrayStreamInfo("text/html",
stream.toByteArray());
}
return null;
}
Alguém saberia me dizer porque toda vez que o sistema chega nessa linha OutputStream ouputStream = response.getOutputStream(); na classe JasperReportFactory é gerada essa excessão?
Ja tentei de tudo mas não consigo resolver esse problema, alguém saberia me dar uma dica?
Obrigado e espero que possam me ajudar!