springboot使用jasper实现报表demo

概述

业务中尝尝需要用到报表数据的渲染和导出.报表的配置势必不能写死,需要动态配置。

现成的JasperReports + Jaspersoft Studio即可实现可配置的报表。

报表布局Jaspersoft Studio

https://community.jaspersoft.com/community-download
下载布局工具,我的pc是win系统,直接下载了exe直接安装了
在这里插入图片描述

创建布局项目

  1. File->New->Project先创建一个项目
  2. 然后继续File->New->Jasper Report(也可以直接在demo项目上右键New->Jasper
    Report),选择一个竖向A4纸大小的模板

在这里插入图片描述

在这里插入图片描述

设计界面展示

  1. Title:标题区,如果数据有多页只会在第一页打印
  2. Page Header:页头区,多页的情况下每页都会打印
  3. Column Header:列头区,配合下面的Detail区打印列表数据,多页的情况下每页都会打印
  4. Detail:可以新增多个Detail区,可以组合打印出多个列表数据,多页的情况下每页都会打印
  5. Column Footer:列表底部区,多页的情况下每页都会打印
  6. Page Footer:页底部区,多页的情况下每页都会打印
  7. Summary:合计区,只会在最后一页打印

在这里插入图片描述

创建完项目后–报表demo

  1. 从右侧Basic Elements区域拖拽一个Static Text元素到Title区,选中元素后,可以在右侧设置元素的边框,字体和大小,文本的对齐方式等等。
  2. 在左侧Outline区域Paramters上右键Create Paramter创建一个新的属性,命名为name,类型java.lang.String
  3. 拖拽name属性到Page Header区域,同样可以在右侧设置它的属性
  4. 在左侧Outline区域Fields上右键 Create Field创建两个字段Field1,Field2,类型java.lang.String
  5. 然后拖拽Field1,Field2字段到Detail1区域,会自动带出两个值为Field1,Field2Static Text元素在Column Header区域,调整位置对齐
  6. 右键jrxml文件可以预览看看样式,因为此时我们未给Field1,Field2的数据集赋值,所以预览的为null
  7. jrxml文件上右键Compile Report可以生成编译生成jasper文件

操作图例

设置title
在这里插入图片描述
添加Paramters
在这里插入图片描述
设置Paramters
在这里插入图片描述

设置field
在这里插入图片描述

预览
在这里插入图片描述

添加图片
需要在field或者Paramters,我在demo中是设置的field

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

变量名需要和上面设置的field变量名对上
在这里插入图片描述

编译
在这里插入图片描述

springboot中调用模板

引入依赖

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

工具类

package com.fchan.jasper.util;

import lombok.extern.slf4j.Slf4j;
import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.export.HtmlExporter;
import net.sf.jasperreports.export.HtmlExporterOutput;
import net.sf.jasperreports.export.SimpleExporterInput;
import net.sf.jasperreports.export.SimpleHtmlExporterOutput;
import net.sf.jasperreports.export.SimpleHtmlReportConfiguration;
import org.springframework.core.io.ClassPathResource;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

/**
 * Author: xyyz150
 * Date: 2020/4/9 19:40
 * Description:
 */
@Slf4j
public class JasperReportUtil {
    final static String jasperDir = "jaspers";

    public static String getJasperFileDir(String fileName) {
        return jasperDir + File.separator + fileName + ".jasper";
    }

    private static String getContentType(ReportType type) {
        String contentType;
        switch (type) {
            case HTML:
                contentType = "text/html;charset=utf-8";
                break;
            case PDF:
                contentType = "application/pdf";
                break;
            case XLS:
                contentType = "application/vnd.ms-excel";
                break;
            case XLSX:
                contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                break;
            case XML:
                contentType = "text/xml";
                break;
            case RTF:
                contentType = "application/rtf";
                break;
            case CSV:
                contentType = "text/plain";
                break;
            case DOC:
                contentType = "application/msword";
                break;
            default:
                contentType = "text/html;charset=utf-8";
        }
        return contentType;
    }

    static JasperPrint getJasperPrint(InputStream jasperStream, Map parameters, List<?> list) throws JRException {
        JRDataSource dataSource = null;
        if (null == list || list.size() == 0) {
            dataSource = new JREmptyDataSource();
        } else {
            dataSource = new JRBeanCollectionDataSource(list);
        }
        JasperPrint jasperPrint = JasperFillManager.fillReport(jasperStream, parameters, dataSource);
        return jasperPrint;
    }

    public static void exportToPdf(String jasperPath, Map parameters, List<?> list, HttpServletResponse response) throws Exception {
        OutputStream outputStream = response.getOutputStream();
        try {
            ClassPathResource resource = new ClassPathResource(jasperPath);
            response.setContentType(getContentType(ReportType.PDF));
            InputStream jasperStream = resource.getInputStream();
            JasperPrint jasperPrint = getJasperPrint(jasperStream, parameters, list);
            JasperExportManager.exportReportToPdfStream(jasperPrint, outputStream);
        } catch (Exception e) {
            log.error("读取报表异常", e);
            outputStream.write("读取报表异常".getBytes());
        } finally {
            outputStream.flush();
            outputStream.close();
        }
    }


    public static void exportToXml(String jasperPath, Map parameters, List<?> list, HttpServletResponse response) throws Exception {
        OutputStream outputStream = response.getOutputStream();
        try {
            ClassPathResource resource = new ClassPathResource(jasperPath);
            response.setContentType(getContentType(ReportType.XML));
            InputStream jasperStream = resource.getInputStream();
            JasperPrint jasperPrint = getJasperPrint(jasperStream, parameters, list);
            JasperExportManager.exportReportToXmlStream(jasperPrint, outputStream);
        } catch (Exception e) {
            log.error("读取报表异常", e);
            outputStream.write("读取报表异常".getBytes());
        } finally {
            outputStream.flush();
            outputStream.close();
        }
    }

    public static void exportToHtml(String jasperPath, Map parameters, List<?> list, HttpServletResponse response) throws Exception {
        response.setHeader("Content-type", "text/html;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType(getContentType(ReportType.HTML));
        PrintWriter out = response.getWriter();
        HtmlExporter exporter = new HtmlExporter();
        try {
            ClassPathResource resource = new ClassPathResource(jasperPath);
            InputStream jasperStream = resource.getInputStream();
            JasperPrint jasperPrint = getJasperPrint(jasperStream, parameters, list);


            exporter.setExporterInput(new SimpleExporterInput(jasperPrint));

            SimpleHtmlReportConfiguration configuration = new SimpleHtmlReportConfiguration();
            exporter.setConfiguration(configuration);

            HtmlExporterOutput outPut = new SimpleHtmlExporterOutput(out);
            exporter.setExporterOutput(outPut);

            exporter.exportReport();
        } catch (Exception e) {
            log.error("读取报表异常", e);
            out.write("读取报表异常");
        } finally {
            out.flush();
            out.close();
        }
    }


 	/**
     * 发送打印任务至打印机
     * @param jasperPath
     * @param parameters
     * @param list
     * @throws Exception
     */
    public static void exportToPdfByPrinter(String jasperPath, Map parameters, List<?> list) throws Exception {
        try {
            ClassPathResource resource = new ClassPathResource(jasperPath);
            InputStream jasperStream = resource.getInputStream();
            JasperPrint jasperPrint = getJasperPrint(jasperStream, parameters, list);


            PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
            DocFlavor flavor = DocFlavor.BYTE_ARRAY.PNG;
            PrintService[] printServices = PrintServiceLookup.lookupPrintServices(flavor, pras);
            for (PrintService printService : printServices) {
                System.out.println(printService.getName());
            }
            //demo默认获取第一个打印机进行打印,实际业务中可以选择所需要的打印机,
            PrintService printService = printServices[0];

            JRAbstractExporter je = new JRPrintServiceExporter();
            je.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);

            //设置指定打印机
            je.setParameter(JRPrintServiceExporterParameter.PRINT_SERVICE, printService);
            je.setParameter(JRPrintServiceExporterParameter.DISPLAY_PAGE_DIALOG, false);
            je.setParameter(JRPrintServiceExporterParameter.DISPLAY_PRINT_DIALOG, false);

            //打印
            je.exportReport();
            jasperStream.close();
        } catch (Exception e) {
            log.error("读取报表异常", e);
        }
    }



    public enum ReportType {
        HTML,
        PDF,
        XLS,
        XLSX,
        XML,
        RTF,
        CSV,
        DOC
    }
}

controller

package com.fchan.jasper.controller;


import com.fchan.jasper.util.JasperReportUtil;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("jasper")
public class MyJasperController {



    @GetMapping("/export")
    public void getReport(@RequestParam("type") String reportType, HttpServletResponse response)
            throws Exception {
        HashMap<String, Object> parameters = new HashMap<String, Object>();
        parameters.put("name", "xiao ming");

        List<HashMap> list = new ArrayList<>();
        for (int i = 0; i < 100; i++) {
            HashMap<String, String> item = new HashMap<String, String>();
            item.put("Field1",  "Field1-" + i);
            item.put("Field2",  "Field2-" + i);
            //图片可以填链接
            item.put("reportDescImage",  "https://i.328888.xyz/2023/04/24/iS185a.jpeg");
            //也可以填写本地图片文件路径
            //item.put("reportDescImage",  "D:\\BaiduNetdiskDownload\\my_huckleberry_friends.jpg");
            list.add(item);
        }
        String jasperPath = JasperReportUtil.getJasperFileDir("demo");
        if (reportType.equals("pdf")) {
            JasperReportUtil.exportToPdf(jasperPath, parameters, list, response);
        } else if (reportType.equals("html")) {
            JasperReportUtil.exportToHtml(jasperPath, parameters, list, response);
        }
    }


}

jasper报表模板文件
在这里插入图片描述

参考了大佬的博文,在最新的jasper上实践了一遍
https://www.cnblogs.com/xyyz120/p/12681245.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值