概述
业务中尝尝需要用到报表数据的渲染和导出.报表的配置势必不能写死,需要动态配置。
现成的JasperReports + Jaspersoft Studio即可实现可配置的报表。
报表布局Jaspersoft Studio
https://community.jaspersoft.com/community-download
下载布局工具,我的pc是win系统,直接下载了exe直接安装了
创建布局项目
- File->New->Project先创建一个项目
- 然后继续File->New->Jasper Report(也可以直接在demo项目上右键New->Jasper
Report),选择一个竖向A4纸大小的模板
设计界面展示
Title
:标题区,如果数据有多页只会在第一页打印Page Header
:页头区,多页的情况下每页都会打印Column Header
:列头区,配合下面的Detail
区打印列表数据,多页的情况下每页都会打印Detail
:可以新增多个Detail
区,可以组合打印出多个列表数据,多页的情况下每页都会打印Column Footer
:列表底部区,多页的情况下每页都会打印Page Footer
:页底部区,多页的情况下每页都会打印Summary
:合计区,只会在最后一页打印
创建完项目后–报表demo
- 从右侧
Basic Elements
区域拖拽一个Static Text
元素到Title
区,选中元素后,可以在右侧设置元素的边框,字体和大小,文本的对齐方式等等。 - 在左侧
Outline
区域Paramters
上右键Create Paramter
创建一个新的属性,命名为name
,类型java.lang.String
- 拖拽
name
属性到Page Header
区域,同样可以在右侧设置它的属性 - 在左侧
Outline
区域Fields
上右键Create Field
创建两个字段Field1,Field2
,类型java.lang.String
- 然后拖拽
Field1,Field2
字段到Detail1
区域,会自动带出两个值为Field1,Field2
的Static Text
元素在Column Header
区域,调整位置对齐 - 右键
jrxml
文件可以预览看看样式,因为此时我们未给Field1,Field2
的数据集赋值,所以预览的为null - 在
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