使用 JRBeanCollectionDataSource 创建 Jasper 报告(PDF、Excel、Csv)时没问题。这意味着 .jrxml 文件接受 pojo 的集合作为处理报告的输入。
现在,我一直在尝试使用相同的 .jrxml 但来自 JSON 对象来创建 jasper 报告。 我尝试了以下操作,但 pdf 报告中的所有值均为空
Resource resource = new ClassPathXmlApplicationContext().getResource("classpath:reports/project.jrxml");
JsonDataSource ds = new JsonDataSource(new File("c:\myjson.json"));
jasperDesign = JRXmlLoader.load(resource.getInputStream());
JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, ds);
JasperExportManager.exportReportToPdfFile(jasperPrint, destination+fileName+".pdf");
谁能帮帮我?
最佳答案
我一直在努力使用 JSON 作为 Jasper 报告的数据源,并且由于网络上缺乏像样的示例,我想我会在此处发布以供将来引用。
此示例是如何使用 iReport Designer 和 JSON 数据源。
首先,输入JSON:
{
"userName": "Evil Raat",
"details": {
"email": "not_really@test.com"
}
}
然后在 iReport Designer 中创建一个 JSON 数据源并将其指向您的文件(将所有其他详细信息保留为默认值)
接下来你可以使用下面的jrxml模板将上面的JSON渲染成一个报告:
<?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="sample" language="groovy" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="a894078a-929b-4aae-a1d0-46485f0f8835">
<property name="ireport.zoom" value="1.0"/>
<property name="ireport.x" value="0"/>
<property name="ireport.y" value="0"/>
<queryString language="json">
<![CDATA[]]>
</queryString>
<field name="userName" class="java.lang.String">
<fieldDescription><![CDATA[userName]]></fieldDescription>
</field>
<field name="userEmail" class="java.lang.String">
<fieldDescription><![CDATA[details.email]]></fieldDescription>
</field>
<title>
<band height="200" splitType="Stretch">
<textField>
<reportElement uuid="3b74775b-4555-43c3-bdf2-1677145c8660" x="0" y="31" width="555" height="20"/>
<textElement textAlignment="Right">
<font fontName="Helvetica" size="12" isBold="true"/>
</textElement>
<textFieldExpression><![CDATA[$F{userName}]]></textFieldExpression>
</textField>
<textField>
<reportElement uuid="aa6cc7c8-2ca1-4f0f-92e2-c466083daba0" x="0" y="54" width="555" height="20"/>
<textElement textAlignment="Right">
<font fontName="Helvetica" size="12" isBold="true"/>
</textElement>
<textFieldExpression><![CDATA[$F{userEmail}]]></textFieldExpression>
</textField>
</band>
</title>
</jasperReport>
注意:您必须先定义字段元素,然后才能使用它们。它们应该是使用标准点表示法从 JSON 输入文件的根开始的 JSON 路径。有关示例,请参见上面的 fieldDescription 元素。
定义字段后,您可以在文本字段或其他任何地方使用它的计算值:
希望对一些人有所帮助。
关于java - 从 JSON 对象或 JSON 字符串创建 Jasper Report PDF 表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11536995/