背景
在开发JasperReports生成报表过程中,想直接用List数据来生成报表,不想连数据库(主要网上的CV太多,全是用JavaBean连接数据源的方式)。*想不通为啥大家都喜欢为了生成个报表跑专门数据库。*无意中找到个方法可以不用连接数据源,写下来分享一下。
环境
| 环境 | 版本 |
|---|---|
| Java | 1.8 |
| IReport | 5.6.0 |
| JasperReports | 6.17.0 |
依赖
jasper依赖
<dependency>
<groupId>net.sf.jasperreports</groupId>
<artifactId>jasperreports</artifactId>
<version>6.17.0</version>
</dependency>
<dependency>
<groupId>net.sf.jasperreports</groupId>
<artifactId>jasperreports-fonts</artifactId>
<version>6.17.0</version>
</dependency>
itext依赖(iTextAsian.jar和iTextAsianCmaps.jar)一般在安装的iReport目录下都有,但是mvn仓库找不到,官方不给下了可还行
<dependency>
<groupId>com.lowagie</groupId>
<artifactId>iTextAsian</artifactId>
<version>1.0</version>
<scope>system</scope>
<systemPath>${project.basedir}/src/main/resources/lib/iTextAsian.jar</systemPath>
</dependency>
<dependency>
<groupId>com.lowagie</groupId>
<artifactId>iTextAsianCmaps</artifactId>
<version>1.0</version>
<scope>system</scope>
<systemPath>${project.basedir}/src/main/resources/lib/iTextAsianCmaps.jar</systemPath>
</dependency>
<!-- https://mvnrepository.com/artifact/org.codehaus.groovy/groovy-all -->
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all</artifactId>
<version>3.0.9</version>
<type>pom</type>
</dependency>
创建模板
过程不说了,随便搜一下能出几万篇一毛一样的出来。
调用方法
public static void main(String[] args) throws Exception {
// iReport参数
Map<String, Object> params = new HashMap<>();
params.put("title", "I'm biao ti");
// 自己造几行List假数据
List<Map<String, Object>> list = new ArrayList<>();
for(int i=0;i<10;i++) {
Map<String, Object> map = new HashMap<>();
map.put("uuid", UUID.randomUUID().toString());
map.put("key", i);
map.put("value", "asd"+i);
list.add(map);
}
File file = new File("C:\\Users\\Administrator\\Desktop\\report2.jasper");
FileInputStream fis = new FileInputStream(file);
JasperPrint jasperPrint = JasperFillManager.fillReport(fis, params, buildDataSource(list));
File out = new File("E:/out.pdf");
FileOutputStream fos = new FileOutputStream(out);
byte[] bytes = JasperExportManager.exportReportToPdf(jasperPrint);
fos.write(bytes, 0, bytes.length);
fis.close();
fos.close();
}
重点来了,创建数据源对象
/**
* 将查询到的列表转成数据源格式
* @param list
* @return
*/
private static JsonDataSource buildDataSource(List list) {
try {
String jsonStr = list!=null && list.size()>0?JSON.toJSONString(list):JSON.toJSONString(new ArrayList<>());
InputStream stream = new ByteArrayInputStream(jsonStr.getBytes(StandardCharsets.UTF_8));
return new JsonDataSource(stream);
} catch (JRException e2) {
throw new RuntimeException("报个错压压惊");
}
}
结语
简不简单,惊不惊喜,数据源不想连直接new一个就行了。
版权声明:本文为m0_46267097原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。