5

I want to create CSV with Jasper Reports. There are many related questions, but nothing is working for me. Below is my bean class:

public class DataBean {

    public String First_name;
    public String Last_name;
    public String Designation;
    public String Department;

    public void setfirstName(String First_name) {
        this.First_name = First_name;
    }

    public String getfirstName() {
        return First_name;
    } 

    public void setLastName(String Last_name) {
        this.Last_name = Last_name;
    }
    public String getlastName() {
        return Last_name;
   }
    public void setdesignation(String Designation) {
        this.Designation = Designation;
    }
    public String getdesignation() {
       return Designation;
    }
    public void setDepartment(String Department) {
        this.Department = Department;
    }
    public String getDepartment() {
        return Department;
    }
}

Below is class which get data from database and generate CSV with Jasper Report:

import java.util.HashMap;
import java.util.Map;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.export.JRCsvExporter;
import net.sf.jasperreports.engine.export.JRCsvExporterParameter;
import net.sf.jasperreports.engine.xml.JRXmlLoader;

import com.mysql.jdbc.PreparedStatement;


public class GetResult 
{
    PreparedStatement pst=null;
    DBConnection dbcon=null;
    String First_name;
    String Last_name;
    String Designation;
    String Department;
    net.sf.jasperreports.engine.JasperReport report = null;
    JasperDesign design = null;
    JasperPrint print = null;
    InputStream input = null;
    public void result(){
        try{
            dbcon=new DBConnection();
            input = new FileInputStream(new File("C:/Users/adiuser1/report2.jrxml"));//report2.jasper
           design = JRXmlLoader.load(input);
            ArrayList<DataBean> al2=new ArrayList<DataBean>();
            Map<String, Object> parameters = new HashMap<String, Object>();
            pst = (PreparedStatement) dbcon.conn.prepareStatement("SELECT First_name, Last_name,     Designation, Department FROM emp_data");
            java.sql.ResultSet rs=pst.executeQuery();
            parameters.put("First_name","First_name");
            parameters.put("Last_name","Last_name");
           parameters.put("Designation","Designation");
           parameters.put("Department","Department");
           while(rs.next())
           {
                DataBean db=new DataBean();
                First_name = rs.getString("First_name");
                db.setfirstName(First_name);    
                Last_name = rs.getString("Last_name");
                db.setLastName(Last_name);
                Designation = rs.getString("Designation");
                db.setdesignation(Designation);
                Department = rs.getString("Department");
                db.setDepartment(Department);
                al2.add(db);
            }
            System.out.println("size: "+parameters.size());
            System.out.println("size: "+al2.size());
            report = JasperCompileManager.compileReport(design);
            JRBeanCollectionDataSource masterDS = null;
            masterDS = new JRBeanCollectionDataSource(al2,false);
            print = JasperFillManager.fillReport(report, parameters, masterDS);
            JRCsvExporter csvExporter = new JRCsvExporter();
            csvExporter.setParameter(JRCsvExporterParameter.JASPER_PRINT, print);
            csvExporter.setParameter(JRCsvExporterParameter.OUTPUT_FILE_NAME, "X:/abc.csv");
            csvExporter.setParameter(JRCsvExporterParameter.CHARACTER_ENCODING, "ISO-8859-1");
            csvExporter.exportReport();
       }
        catch(JRException jrException)
        {
            System.out.print(jrException);
            jrException.printStackTrace();
        }
       catch(Exception e)
       {
           System.out.println(e);
      }
      }
   public static void main(String ...s)
   {
        GetResult gr=new GetResult();
       gr.result();
  }
}

Below is my jrxml :

<?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="report2" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" isIgnorePagination="true" uuid="204c18b7-de66-4171-b8b8-82a20b837f28">
<property name="ireport.zoom" value="1.0"/>
<property name="ireport.x" value="0"/>
<property name="ireport.y" value="0"/>
<subDataset name="sum" uuid="73ad5db5-041e-4e27-aed3-acaf6deec1b8">
    <queryString language="SQL">
        <![CDATA[]]>
    </queryString>
    <field name="First_name" class="java.lang.String"/>
    <field name="Last_name" class="java.lang.String"/>
    <field name="Designation" class="java.lang.String"/>
    <field name="Department" class="java.lang.String"/>
</subDataset>
<field name="First_name" class="java.lang.String">
    <fieldDescription><![CDATA[]]></fieldDescription>
</field>
<field name="Last_name" class="java.lang.String">
    <fieldDescription><![CDATA[]]></fieldDescription>
</field>
<field name="Designation" class="java.lang.String">
    <fieldDescription><![CDATA[]]></fieldDescription>
</field>
<field name="Department" class="java.lang.String">
    <fieldDescription><![CDATA[]]></fieldDescription>
</field>
<background>
    <band splitType="Stretch"/>
</background>
<columnHeader>
    <band height="35" splitType="Stretch">
        <staticText>
            <reportElement uuid="2322e160-4c43-4027-af14-3c69a4d236ed" x="8" y="4" width="100" height="20" backcolor="#003333"/>
            <textElement/>
            <text><![CDATA[First_name]]></text>
        </staticText>
        <staticText>
            <reportElement uuid="a5f84e13-ffee-491f-aa52-602b7b4e9c99" x="149" y="4" width="100" height="20" forecolor="#9999FF" backcolor="#00FFFF"/>
            <textElement/>
            <text><![CDATA[Last_name]]></text>
        </staticText>
        <staticText>
            <reportElement uuid="cd216988-6061-4ef2-8f4d-18e31cabd9e1" x="299" y="4" width="100" height="20"/>
            <textElement/>
            <text><![CDATA[Designation]]></text>
        </staticText>
        <staticText>
            <reportElement uuid="22587697-d3b8-4a55-b81d-d380a4e19a7a" x="433" y="4" width="100" height="20"/>
            <textElement/>
            <text><![CDATA[Department]]></text>
        </staticText>
    </band>
</columnHeader>
<detail>
    <band height="26" splitType="Stretch">
        <textField>
            <reportElement uuid="3f6821a6-3aa1-418f-aa68-25b844256276" key="First_name" x="8" y="0" width="100" height="21"/>
            <textElement/>
            <textFieldExpression><![CDATA[$F{First_name}]]></textFieldExpression>
        </textField>
        <textField>
            <reportElement uuid="e453bc45-a734-4db6-bba5-19a24252d3ba" x="149" y="0" width="100" height="20"/>
            <textElement/>
            <textFieldExpression><![CDATA[$F{Last_name}]]></textFieldExpression>
        </textField>
        <textField>
            <reportElement uuid="5c604a9d-5dba-4b47-9e8c-41de0a29323c" x="299" y="0" width="100" height="20"/>
            <textElement/>
            <textFieldExpression><![CDATA[$F{Designation}]]></textFieldExpression>
        </textField>
        <textField>
            <reportElement uuid="fa2e53f2-ff71-485d-b9ef-0259ace3eabb" x="433" y="0" width="100" height="20"/>
            <textElement/>
            <textFieldExpression><![CDATA[$F{Department}]]></textFieldExpression>
        </textField>
    </band>
</detail>
<columnFooter>
    <band height="45" splitType="Stretch"/>
</columnFooter>
<pageFooter>
    <band height="54" splitType="Stretch"/>
</pageFooter>
<summary>
    <band height="42" splitType="Stretch"/>
</summary>
</jasperReport>

While i run GetResult.java it gives following error:

net.sf.jasperreports.engine.JRException: Error retrieving field value from bean : First_namenet.sf.jasperreports.engine.JRException: Error retrieving field value from bean : First_name
at net.sf.jasperreports.engine.data.JRAbstractBeanDataSource.getBeanProperty(JRAbstractBeanDataSource.java:123)
at net.sf.jasperreports.engine.data.JRAbstractBeanDataSource.getFieldValue(JRAbstractBeanDataSource.java:96)
at net.sf.jasperreports.engine.data.JRBeanCollectionDataSource.getFieldValue(JRBeanCollectionDataSource.java:100)
at net.sf.jasperreports.engine.fill.JRFillDataset.setOldValues(JRFillDataset.java:1331)
at net.sf.jasperreports.engine.fill.JRFillDataset.next(JRFillDataset.java:1232)
at net.sf.jasperreports.engine.fill.JRFillDataset.next(JRFillDataset.java:1208)
at net.sf.jasperreports.engine.fill.JRBaseFiller.next(JRBaseFiller.java:1577)
at net.sf.jasperreports.engine.fill.JRVerticalFiller.fillReport(JRVerticalFiller.java:149)
at net.sf.jasperreports.engine.fill.JRBaseFiller.fill(JRBaseFiller.java:932)
at net.sf.jasperreports.engine.fill.JRBaseFiller.fill(JRBaseFiller.java:864)
at net.sf.jasperreports.engine.fill.JRFiller.fill(JRFiller.java:88)
at net.sf.jasperreports.engine.JasperFillManager.fill(JasperFillManager.java:653)
at net.sf.jasperreports.engine.JasperFillManager.fillReport(JasperFillManager.java:969)
at GetResult.result(GetResult.java:78)
at GetResult.main(GetResult.java:99)
Caused by: java.lang.NoSuchMethodException: Unknown property 'First_name'
at org.apache.commons.beanutils.PropertyUtils.getSimpleProperty(PropertyUtils.java:1175)
at org.apache.commons.beanutils.PropertyUtils.getNestedProperty(PropertyUtils.java:772)
at org.apache.commons.beanutils.PropertyUtils.getProperty(PropertyUtils.java:801)
at     net.sf.jasperreports.engine.data.JRAbstractBeanDataSource.getBeanProperty(JRAbstractBeanDataSource.java:111)
... 14 more

Please help me to resolve this problem.

Alex K
  • 22,315
  • 19
  • 108
  • 236
Sumit Kamboj
  • 846
  • 2
  • 10
  • 17
  • its jasperReport error i think you should use subdataset fields in you report to display values, using datasetRun like this [multiple-queries-in-a-single-jasper-document](http://stackoverflow.com/questions/7482412/multiple-queries-in-a-single-jasper-document). my suggestion that you should try with different names i see many First_name. Try auto generating getters, setters in dataBean – techGaurdian Dec 19 '14 at 05:34
  • That "DataBean" field and getter/setter naming sent a chill down my spine – Daniel Higueras Oct 04 '16 at 10:40

3 Answers3

10

Rename your fields to start with lowercase letters, and your getter and setter methods to correspond. Like:

String firstName;
public String getFirstName() {
    return firstName;
} 
public void setFirstName(String First_name) {
        this.firstName= First_name;
}

Jasper looks for the corresponding getter that respects java convensions.

Laura
  • 1,552
  • 12
  • 12
  • 2
    It is the right way. But in addition questioner must rename field $F{First_name} to $F{firstName} in JRXML. After that field name in JRXML will corresponds with getter. – sanBez Dec 19 '14 at 10:44
  • Thanks guys....one more help, column header is not showing in CSV file and could you please tell me how to fill colour in cell? – Sumit Kamboj Dec 19 '14 at 11:32
  • 1. column header in csv: I Dont't know 2. fill color: AFAIR, you must define backColor and opaque property, for instance `` – sanBez Dec 19 '14 at 14:27
  • @SanBez fill color is working only when out file format is XLS. It's not working when file format is CSV. any clue about his issue? – Sumit Kamboj Dec 29 '14 at 07:19
  • @Madhuka Dilhan details? – Laura Feb 22 '18 at 09:33
0

Just rename the field in the report file to start in lowercase. And then if you need the field on the report to start with uppercase you just change it on the design paper (static text). This is my code, I think it similar to yours:

<queryString>
    <![CDATA[]]>
</queryString>
<field name="no" class="java.lang.Integer"/>
<field name="pname" class="java.lang.String"/>
<field name="price" class="java.lang.Double"/>
<field name="qty" class="java.lang.Integer"/>
<variable name="DisPrice" class="java.lang.Double">

//-------------------------------------------------------------------------------

    <band height="33" splitType="Stretch">
        <staticText>
            <reportElement x="0" y="0" width="51" height="16" uuid="f536be7a-1840-45d5-9e9f-4b12989e2a07">
                <property name="com.jaspersoft.studio.spreadsheet.connectionID" value="7a4542c6-45f9-4419-8e89-80eb899c9cf6"/>
                <property name="com.jaspersoft.studio.unit.height" value="px"/>
            </reportElement>
            <textElement textAlignment="Center">
                <font isBold="true"/>
            </textElement>
            <text><![CDATA[No]]></text>
        </staticText>
        <staticText>
            <reportElement x="51" y="0" width="49" height="16" uuid="5a327b35-9607-4a80-bd21-0094c8c410b8">
                <property name="com.jaspersoft.studio.spreadsheet.connectionID" value="97cae40e-39c1-4920-84ad-21829e4f3260"/>
                <property name="com.jaspersoft.studio.unit.height" value="px"/>
            </reportElement>
            <textElement textAlignment="Center">
                <font isBold="true"/>
            </textElement>
            <text><![CDATA[Pname]]></text>
        </staticText>
        <staticText>
            <reportElement x="100" y="0" width="49" height="16" uuid="dd5b5d95-f25a-4fa1-99fc-988818bc33d4">
                <property name="com.jaspersoft.studio.spreadsheet.connectionID" value="7e127586-4648-4239-b23c-dbeb38e8024a"/>
                <property name="com.jaspersoft.studio.unit.height" value="px"/>
            </reportElement>
            <textElement textAlignment="Center">
                <font isBold="true"/>
            </textElement>
            <text><![CDATA[Price]]></text>
        </staticText>
        <staticText>
            <reportElement x="149" y="0" width="49" height="16" uuid="6b286509-8c9b-4ed4-add2-ae7654b63842">
                <property name="com.jaspersoft.studio.spreadsheet.connectionID" value="3967222c-bc54-4251-927c-7991b086e3ce"/>
                <property name="com.jaspersoft.studio.unit.height" value="px"/>
            </reportElement>
            <textElement textAlignment="Center">
                <font isBold="true"/>
            </textElement>
            <text><![CDATA[Qty]]></text>
        </staticText>
    </band>
0

There are three things needs to be addressed:

  1. Rename your fields to start with lowercase letters, and your getter and setter methods to correspond.
  2. You should update the java build path to jdk 11 in Jasper property setting (Jasper studio -> Project -> Properties -> Java Build Path).enter image description here
  3. Make sure your implementation 'net.sf.jasperreports:jasperreports:6.2.0' version match the compilation version in Jasper property setting (Jasper studio -> Project -> Properties -> Jasper Studio -> Compatibility).enter image description here