Loading

在项目中输出运营数据PDF报表

本小节我们将在项目中实现运营数据的PDF报表导出功能。

设计PDF模板文件

使用Jaspersoft Studio设计运营数据PDF报表模板文件health_business3.jrxml,设计后的效果如下:

在资源中已经提供好了此文件,直接使用即可。

搭建环境

第一步:在health_common工程的pom.xml中导入JasperReports的maven坐标

<dependency>
    <groupId>net.sf.jasperreports</groupId>
    <artifactId>jasperreports</artifactId>
    <version>6.8.0</version>
</dependency>

第二步:将资源中提供的模板文件health_business3.jrxml复制到health_backend工程的template目录下

第三步:将解决中问题的相关资源文件复制到项目中

修改页面

修改health_backend工程的report_business.html页面,添加导出PDF的按钮并绑定事件

Java代码实现

在health_backend工程的ReportController中提供exportBusinessReport4PDF方法

//导出运营数据到pdf并提供客户端下载
@RequestMapping("/exportBusinessReport4PDF")
public Result exportBusinessReport4PDF(HttpServletRequest request, HttpServletResponse response) {
    try {
        Map<String, Object> result = reportService.getBusinessReportData();
​
        //取出返回结果数据,准备将报表数据写入到PDF文件中
        List<Map> hotSetmeal = (List<Map>) result.get("hotSetmeal");
​
        //动态获取模板文件绝对磁盘路径
        String jrxmlPath = 
            request.getSession().getServletContext().getRealPath("template") + File.separator + "health_business3.jrxml";
        String jasperPath = 
            request.getSession().getServletContext().getRealPath("template") + File.separator + "health_business3.jasper";
        //编译模板
        JasperCompileManager.compileReportToFile(jrxmlPath, jasperPath);
​
        //填充数据---使用JavaBean数据源方式填充
        JasperPrint jasperPrint =
            JasperFillManager.fillReport(jasperPath,result,
                                         new JRBeanCollectionDataSource(hotSetmeal));
​
        ServletOutputStream out = response.getOutputStream();
        response.setContentType("application/pdf");
        response.setHeader("content-Disposition", "attachment;filename=report.pdf");
​
        //输出文件
        JasperExportManager.exportReportToPdfStream(jasperPrint,out);
​
        return null;
    } catch (Exception e) {
        e.printStackTrace();
        return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL);
    }
}

 

posted @ 2021-07-15 12:40  1640808365  阅读(171)  评论(0编辑  收藏  举报