我使用 ireport 设计了 jasper 报告,我想从 jsp 调用该报告,并且我使用 sql 查询构建了报告。
最佳答案
您需要在单击 jsp 文件中的按钮或图像时调用 servlet。在 servlet 中编译你的 jrxml(jasper 报告格式)。然后您需要编写代码来下载该 servlet。
以下代码用于编译 jasper 报告并导出到特定文件夹:
HashMap<String, Object> response = new HashMap<String, Object>();
String fileName = "C:\\temp\\report.jrxml";
String pdfFile = "C:\\temp\\";
JasperReport mainReport;
JasperDesign mainReportDesign;
try {
mainReportDesign = JRXmlLoader.load(fileName);
mainReport = JasperCompileManager.compileReport(mainReportDesign);
if(reportFormat.equalsIgnoreCase("PDF"))
pdfFile = pdfFile+"report.pdf";
else if(reportFormat.equalsIgnoreCase("CSV"))
pdfFile = pdfFile+"report.csv";
JasperPrint jasperPrint = JasperFillManager.fillReport(mainReport, params, new JREmptyDataSource());
if(reportFormat.equalsIgnoreCase("PDF"))
JasperExportManager.exportReportToPdfFile(jasperPrint, pdfFile);
else if(reportFormat.equalsIgnoreCase("CSV")) {
JRExporter exporter = new JRCsvExporter();
exporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, pdfFile);
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporter.exportReport();
}
} catch (JRException e) {
e.printStackTrace();
}
下面的代码用于从该文件夹下载该导出文件。这将在您的 servlet 类中:
File f = new File("C:\\temp\\report.pdf");
int length = 0;
ServletOutputStream op = resp.getOutputStream();
ServletContext context = getServletConfig().getServletContext();
String mimetype = context.getMimeType(f.getName());
resp.setContentType( (mimetype != null) ? mimetype : "application/octet-stream" );
resp.setContentLength( (int)f.length() );
resp.setHeader( "Content-Disposition", "attachment; filename="+reportName );
byte[] bbuf = new byte[1024];
DataInputStream in = new DataInputStream(new FileInputStream(f));
while ((in != null) && ((length = in.read(bbuf)) != -1))
{
op.write(bbuf,0,length);
}
in.close();
op.flush();
op.close();
关于java - 如何在jsp中显示jasper报表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9821347/