SlideShare una empresa de Scribd logo
1 de 11
Descargar para leer sin conexión
REPORTES JASPERREPORT E IREPORT SIN CONEXIÓN A UNA BBDD
En este post vamos a ver como se pasan parámetros desde java al reporte sin necesidad de una conexión a una BBDD, es decir, podemos pasar
los parámetros que queramos.
Vamos a comenzar creando un proyecto nuevo (File/New Project) y una clase en java que utilizaremos para instanciar objetos ( botón derecho
en el paquete y New/java Class) y así pasar los datos al datasource. Para usar de ejemplo, hemos creado la clase Asistentes.
public class Asistentes {
private Integer id;
private String nombre;
private String apellidos;
private String dni;
public Asistentes(){
}
public Asistentes(int id, String nombre, String apellidos, String dni) {
this.id = id;
this.nombre = nombre;
this.apellidos = apellidos;
this.dni = dni;
}
public int getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getApellidos() {
return apellidos;
}
public void setApellidos(String apellidos) {
this.apellidos = apellidos;
}
public String getDni() {
return dni;
}
public void setDni(String dni) {
this.dni = dni;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
}
Esta clase tiene cuatro atributos, constructor por defecto y constructor parametrizado. También debemos incluir los getters and setters ya que
los atributos son privados y necesitaremos asignar esos valores.
A continuación vamos a crear el reporte. Para ello botón derecho en el paquete y nuevo Empty report.
Para editar el reporte vamos a utilizar el programa de
para netbeans). Os lo podéis descargar del siguiente enlace:
http://sourceforge.net/projects/ireport/files/iReport/
En nuestro reporte vamos a asignar etiquetas para las columnas y para el nombre del reporte. Esto se hace con
derecha).
Para editar el reporte vamos a utilizar el programa de iReport, que previamente lo tenemos que tener instalado ( a parte del plugin de iReport
para netbeans). Os lo podéis descargar del siguiente enlace:
http://sourceforge.net/projects/ireport/files/iReport/
En nuestro reporte vamos a asignar etiquetas para las columnas y para el nombre del reporte. Esto se hace con
, que previamente lo tenemos que tener instalado ( a parte del plugin de iReport
En nuestro reporte vamos a asignar etiquetas para las columnas y para el nombre del reporte. Esto se hace con Static Text (Paleta que está a la
Para asignar los valores que van a ir rellenando las diferentes columnas tenemos que crear unas variables y unos campos. Estos campos se
crean pinchando botón derecho en Fields/Agregar Field. Hay que asignarles el tipo de dato (java.lang.String, java.lang.Integer o el que sea), y
debe de coincidir con el tipo de dato que le pasemos en el programa principal, en este caso con el tipo de datos de las variables de nuestra clase
Asistentes.
Una vez creados todos, pinchamos y los arrastramos al reporte. Así quedaría el nuestro:
Muy bien, ahora hay que crear la clase para pasar estos datos. Esta clase tiene que implementar la clase JRDataSource, y tiene dos métodos
que son obligatorios sobreescribir, el método next() y getFieldValue(JRField jrf). En el método next incrementará el contador y JasperReport
sabrá cuantos Asistentes van a existir. El método getFieldValue asignará los valores a los Fields correspondientes.
A parte en esta clase vamos a crear una variable que será una lista de Asistentes y también un método para ir agregando cada asistente a la lista.
La clase quedaría así:
public class AsistentesDataSource implements JRDataSource{
private List<Asistentes> listaAsistentes = new ArrayList<Asistentes>();
private int indiceParticipanteActual = -1;
@Override
public boolean next() throws JRException {
return ++indiceParticipanteActual < listaAsistentes.size();
}
public void addAsistente(Asistentes Asistente){
this.listaAsistentes.add(Asistente);
}
@Override
public Object getFieldValue(JRField jrf) throws JRException {
Object valor = null;
if ("id".equals(jrf.getName())){
valor = listaAsistentes.get(indiceParticipanteActual).getId();
}
else if ("nombre".equals(jrf.getName())){
valor = listaAsistentes.get(indiceParticipanteActual).getNombre();
}
else if ("apellidos".equals(jrf.getName())){
valor = listaAsistentes.get(indiceParticipanteActual).getApellidos();
}
else if ("dni".equals(jrf.getName())){
valor = listaAsistentes.get(indiceParticipanteActual).getDni();
}
return valor;
}
}
En el main() tenemos que inicializar jasperreport y la clase Asistentes. También crear los objetos y pasarlos al datasource además de crear el
reporte. El método main() quedaría de la siguiente forma:
public static void main(String[] args) {
// TODO code application logic here
InputStream inputStream = null;
JasperPrint jasperPrint= null;
AsistentesDataSource datasource = new AsistentesDataSource();
for(int i = 0; i<=5; i++){
Asistentes asist;
asist = new Asistentes(i, "AsistenteNombre de "+i,"AsistenteApellidos de "+i, "Asistente dni de "+i);
datasource.addAsistente(asist);
}
try {
inputStream = new FileInputStream ("src/reportes/reporte01.jrxml");
} catch (FileNotFoundException ex) {
JOptionPane.showMessageDialog(null,"Error al leer el fichero de carga jasper report "+ex.getMessage());
}
try{
JasperDesign jasperDesign = JRXmlLoader.load(inputStream);
JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);
jasperPrint = JasperFillManager.fillReport(jasperReport, null, datasource);
JasperExportManager.exportReportToPdfFile(jasperPrint, "src/reportes/reporte01.pdf");
}catch (JRException e){
JOptionPane.showMessageDialog(null,"Error al cargar fichero jrml jasper report "+e.getMessage());
}
}
Ejecutamos el proyecto ya tenemos nuestro reporte:
Hay problemas con la versión de iReport y Windows. Al ejecutar el proyecto nos puede aparecer dos tipos de errores.
• Error uuid: no está permitido que el atributo uuid aparezca en el elemento jasperreport
• Error cast: can not cast from Integer to String.
Para el error del uuid simplemente en la vista del xml del reporte hay que borrar todos los campos donde venga el uuid. Para el error del cast,
hay que añadir en los <textFieldExpressions> la clase correspondiente (String, Integer,Float,...)
Podéis descargaros el proyecto en GitHub -> https://github.com/sandritascs/ReporteJasperReport
BLOG: http://sandritascs.blogspot.com.es/2015/01/reportes-con-jasperreports-e-ireport.html

Más contenido relacionado

La actualidad más candente

Frame class library and namespace
Frame class library and namespaceFrame class library and namespace
Frame class library and namespaceJaya Kumari
 
Jasper reports in 3 easy steps
Jasper reports in 3 easy stepsJasper reports in 3 easy steps
Jasper reports in 3 easy stepsIvaylo Zashev
 
ASP.NET Core MVC + Web API with Overview
ASP.NET Core MVC + Web API with OverviewASP.NET Core MVC + Web API with Overview
ASP.NET Core MVC + Web API with OverviewShahed Chowdhuri
 
Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]Aaron Gustafson
 
Object oreinted php | OOPs
Object oreinted php | OOPsObject oreinted php | OOPs
Object oreinted php | OOPsRavi Bhadauria
 
Sap sapscripts tips and tricks
Sap sapscripts tips and tricksSap sapscripts tips and tricks
Sap sapscripts tips and tricksKranthi Kumar
 
IBM Datapower Security Scenario with JWS & JWE
IBM Datapower Security Scenario with JWS & JWEIBM Datapower Security Scenario with JWS & JWE
IBM Datapower Security Scenario with JWS & JWEsandipg123
 
ASP.NET Web API and HTTP Fundamentals
ASP.NET Web API and HTTP FundamentalsASP.NET Web API and HTTP Fundamentals
ASP.NET Web API and HTTP FundamentalsIdo Flatow
 
A Short Intorduction to JasperReports
A Short Intorduction to JasperReportsA Short Intorduction to JasperReports
A Short Intorduction to JasperReportsGuo Albert
 
What is Material UI?
What is Material UI?What is Material UI?
What is Material UI?Flatlogic
 
React state
React  stateReact  state
React stateDucat
 
From a monolith to microservices + REST: The evolution of LinkedIn's architec...
From a monolith to microservices + REST: The evolution of LinkedIn's architec...From a monolith to microservices + REST: The evolution of LinkedIn's architec...
From a monolith to microservices + REST: The evolution of LinkedIn's architec...Karan Parikh
 
BÀI THÍ NGHIỆM SỐ XÂY DỰNG HIBERNATE CHO ỨNG DỤNG JAVA_10441312092019
BÀI THÍ NGHIỆM SỐ XÂY DỰNG HIBERNATE CHO ỨNG DỤNG JAVA_10441312092019BÀI THÍ NGHIỆM SỐ XÂY DỰNG HIBERNATE CHO ỨNG DỤNG JAVA_10441312092019
BÀI THÍ NGHIỆM SỐ XÂY DỰNG HIBERNATE CHO ỨNG DỤNG JAVA_10441312092019TiLiu5
 

La actualidad más candente (20)

Frame class library and namespace
Frame class library and namespaceFrame class library and namespace
Frame class library and namespace
 
Spring boot
Spring bootSpring boot
Spring boot
 
Jasper reports in 3 easy steps
Jasper reports in 3 easy stepsJasper reports in 3 easy steps
Jasper reports in 3 easy steps
 
Odata
OdataOdata
Odata
 
ASP.NET Core MVC + Web API with Overview
ASP.NET Core MVC + Web API with OverviewASP.NET Core MVC + Web API with Overview
ASP.NET Core MVC + Web API with Overview
 
React
React React
React
 
Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]
 
Object oreinted php | OOPs
Object oreinted php | OOPsObject oreinted php | OOPs
Object oreinted php | OOPs
 
Sap sapscripts tips and tricks
Sap sapscripts tips and tricksSap sapscripts tips and tricks
Sap sapscripts tips and tricks
 
Volley vs Retrofit
Volley vs RetrofitVolley vs Retrofit
Volley vs Retrofit
 
Php
PhpPhp
Php
 
IBM Datapower Security Scenario with JWS & JWE
IBM Datapower Security Scenario with JWS & JWEIBM Datapower Security Scenario with JWS & JWE
IBM Datapower Security Scenario with JWS & JWE
 
ASP.NET Web API and HTTP Fundamentals
ASP.NET Web API and HTTP FundamentalsASP.NET Web API and HTTP Fundamentals
ASP.NET Web API and HTTP Fundamentals
 
Xke spring boot
Xke spring bootXke spring boot
Xke spring boot
 
Vue JS Intro
Vue JS IntroVue JS Intro
Vue JS Intro
 
A Short Intorduction to JasperReports
A Short Intorduction to JasperReportsA Short Intorduction to JasperReports
A Short Intorduction to JasperReports
 
What is Material UI?
What is Material UI?What is Material UI?
What is Material UI?
 
React state
React  stateReact  state
React state
 
From a monolith to microservices + REST: The evolution of LinkedIn's architec...
From a monolith to microservices + REST: The evolution of LinkedIn's architec...From a monolith to microservices + REST: The evolution of LinkedIn's architec...
From a monolith to microservices + REST: The evolution of LinkedIn's architec...
 
BÀI THÍ NGHIỆM SỐ XÂY DỰNG HIBERNATE CHO ỨNG DỤNG JAVA_10441312092019
BÀI THÍ NGHIỆM SỐ XÂY DỰNG HIBERNATE CHO ỨNG DỤNG JAVA_10441312092019BÀI THÍ NGHIỆM SỐ XÂY DỰNG HIBERNATE CHO ỨNG DỤNG JAVA_10441312092019
BÀI THÍ NGHIỆM SỐ XÂY DỰNG HIBERNATE CHO ỨNG DỤNG JAVA_10441312092019
 

Destacado

Presentación ferrovertex
Presentación ferrovertexPresentación ferrovertex
Presentación ferrovertexSinergia León
 
Varehandel møter offentlig planlegging - Ingunn Kvernstuen, IK Architecture U...
Varehandel møter offentlig planlegging - Ingunn Kvernstuen, IK Architecture U...Varehandel møter offentlig planlegging - Ingunn Kvernstuen, IK Architecture U...
Varehandel møter offentlig planlegging - Ingunn Kvernstuen, IK Architecture U...insam
 
Resultados anuales 2012 syngenta -
Resultados anuales 2012   syngenta -Resultados anuales 2012   syngenta -
Resultados anuales 2012 syngenta -fyo
 
3.3.11 seminar on demand and supply management in services
3.3.11 seminar on demand  and supply management in services3.3.11 seminar on demand  and supply management in services
3.3.11 seminar on demand and supply management in servicesAndrew Seminar
 
Redes sociais para ONs e Comercio local
Redes sociais para ONs e Comercio localRedes sociais para ONs e Comercio local
Redes sociais para ONs e Comercio localManuel Freiría
 
RESUME_ MANJARI DUTTA
RESUME_ MANJARI DUTTARESUME_ MANJARI DUTTA
RESUME_ MANJARI DUTTAManjari Dutta
 
Coming out of the coalmine: the grown up challenges of the internet of things.
Coming out of the coalmine: the grown up challenges of the internet of things.Coming out of the coalmine: the grown up challenges of the internet of things.
Coming out of the coalmine: the grown up challenges of the internet of things.Alexandra Deschamps-Sonsino
 
Deontología pa exponer
Deontología pa exponerDeontología pa exponer
Deontología pa exponerErazoskr
 
Formalizacion Comercial
Formalizacion ComercialFormalizacion Comercial
Formalizacion Comercialasesorcontable
 
EL FOMENTO DEL ESPÍRITU EMPRESARIAL Y EMPRENDEDOR: UN DISCURSO POLITICO O UNA...
EL FOMENTO DEL ESPÍRITU EMPRESARIAL Y EMPRENDEDOR: UN DISCURSO POLITICO O UNA...EL FOMENTO DEL ESPÍRITU EMPRESARIAL Y EMPRENDEDOR: UN DISCURSO POLITICO O UNA...
EL FOMENTO DEL ESPÍRITU EMPRESARIAL Y EMPRENDEDOR: UN DISCURSO POLITICO O UNA...UNIVERSIDAD DE SEVILLA
 
Medicusmundi guiao de planificacao distrital
Medicusmundi guiao de planificacao distritalMedicusmundi guiao de planificacao distrital
Medicusmundi guiao de planificacao distritalEdmundo Caetano
 
T 8 espais sector terciari (1)
T 8 espais sector terciari (1)T 8 espais sector terciari (1)
T 8 espais sector terciari (1)graciajt
 
Marketing Translation for the Beauty Industry - ATA presentation 2009 updated
Marketing Translation for the Beauty Industry - ATA presentation 2009 updatedMarketing Translation for the Beauty Industry - ATA presentation 2009 updated
Marketing Translation for the Beauty Industry - ATA presentation 2009 updatedAgnes Meilhac
 
Recomedic Rehab - presentation (german)
Recomedic Rehab - presentation (german)Recomedic Rehab - presentation (german)
Recomedic Rehab - presentation (german)Recomedic Rehab
 

Destacado (20)

Coordinacion
CoordinacionCoordinacion
Coordinacion
 
Presentación ferrovertex
Presentación ferrovertexPresentación ferrovertex
Presentación ferrovertex
 
Varehandel møter offentlig planlegging - Ingunn Kvernstuen, IK Architecture U...
Varehandel møter offentlig planlegging - Ingunn Kvernstuen, IK Architecture U...Varehandel møter offentlig planlegging - Ingunn Kvernstuen, IK Architecture U...
Varehandel møter offentlig planlegging - Ingunn Kvernstuen, IK Architecture U...
 
Resultados anuales 2012 syngenta -
Resultados anuales 2012   syngenta -Resultados anuales 2012   syngenta -
Resultados anuales 2012 syngenta -
 
4. ICMA Ausschreibung D
4. ICMA Ausschreibung D4. ICMA Ausschreibung D
4. ICMA Ausschreibung D
 
Creativity Jump Start
Creativity Jump StartCreativity Jump Start
Creativity Jump Start
 
3.3.11 seminar on demand and supply management in services
3.3.11 seminar on demand  and supply management in services3.3.11 seminar on demand  and supply management in services
3.3.11 seminar on demand and supply management in services
 
Redes sociais para ONs e Comercio local
Redes sociais para ONs e Comercio localRedes sociais para ONs e Comercio local
Redes sociais para ONs e Comercio local
 
love you mum-Pandas
love you mum-Pandaslove you mum-Pandas
love you mum-Pandas
 
RESUME_ MANJARI DUTTA
RESUME_ MANJARI DUTTARESUME_ MANJARI DUTTA
RESUME_ MANJARI DUTTA
 
Coming out of the coalmine: the grown up challenges of the internet of things.
Coming out of the coalmine: the grown up challenges of the internet of things.Coming out of the coalmine: the grown up challenges of the internet of things.
Coming out of the coalmine: the grown up challenges of the internet of things.
 
Deontología pa exponer
Deontología pa exponerDeontología pa exponer
Deontología pa exponer
 
Jobhunting
JobhuntingJobhunting
Jobhunting
 
Formalizacion Comercial
Formalizacion ComercialFormalizacion Comercial
Formalizacion Comercial
 
EL FOMENTO DEL ESPÍRITU EMPRESARIAL Y EMPRENDEDOR: UN DISCURSO POLITICO O UNA...
EL FOMENTO DEL ESPÍRITU EMPRESARIAL Y EMPRENDEDOR: UN DISCURSO POLITICO O UNA...EL FOMENTO DEL ESPÍRITU EMPRESARIAL Y EMPRENDEDOR: UN DISCURSO POLITICO O UNA...
EL FOMENTO DEL ESPÍRITU EMPRESARIAL Y EMPRENDEDOR: UN DISCURSO POLITICO O UNA...
 
Medicusmundi guiao de planificacao distrital
Medicusmundi guiao de planificacao distritalMedicusmundi guiao de planificacao distrital
Medicusmundi guiao de planificacao distrital
 
Seguridad en VoIP
Seguridad en VoIPSeguridad en VoIP
Seguridad en VoIP
 
T 8 espais sector terciari (1)
T 8 espais sector terciari (1)T 8 espais sector terciari (1)
T 8 espais sector terciari (1)
 
Marketing Translation for the Beauty Industry - ATA presentation 2009 updated
Marketing Translation for the Beauty Industry - ATA presentation 2009 updatedMarketing Translation for the Beauty Industry - ATA presentation 2009 updated
Marketing Translation for the Beauty Industry - ATA presentation 2009 updated
 
Recomedic Rehab - presentation (german)
Recomedic Rehab - presentation (german)Recomedic Rehab - presentation (german)
Recomedic Rehab - presentation (german)
 

Similar a Reportes Jasper sin BBDD

Similar a Reportes Jasper sin BBDD (20)

P2C2 Introducción a JEE5
P2C2 Introducción a JEE5P2C2 Introducción a JEE5
P2C2 Introducción a JEE5
 
Agregación Composición
Agregación ComposiciónAgregación Composición
Agregación Composición
 
Agregacion composicion
Agregacion composicionAgregacion composicion
Agregacion composicion
 
Clase 1 Programacion Android
Clase 1 Programacion AndroidClase 1 Programacion Android
Clase 1 Programacion Android
 
C# calculadora
C# calculadoraC# calculadora
C# calculadora
 
Carro De Compras
Carro De ComprasCarro De Compras
Carro De Compras
 
Persistencia avanzada de datos en Java. JPA
Persistencia avanzada de datos en Java. JPAPersistencia avanzada de datos en Java. JPA
Persistencia avanzada de datos en Java. JPA
 
Trabajo de consulta
Trabajo de consultaTrabajo de consulta
Trabajo de consulta
 
Tips componentes swing_v5
Tips componentes swing_v5Tips componentes swing_v5
Tips componentes swing_v5
 
6. tda arrayu generico
6. tda arrayu generico6. tda arrayu generico
6. tda arrayu generico
 
Clase7 generics
Clase7 genericsClase7 generics
Clase7 generics
 
Arreglos, Procedimientos y Funciones
Arreglos, Procedimientos y FuncionesArreglos, Procedimientos y Funciones
Arreglos, Procedimientos y Funciones
 
Array listlistas
Array listlistasArray listlistas
Array listlistas
 
Clase3 asignaciones
Clase3 asignacionesClase3 asignaciones
Clase3 asignaciones
 
ED 02 2_tda_arra_u
ED 02 2_tda_arra_uED 02 2_tda_arra_u
ED 02 2_tda_arra_u
 
Java paratodos1
Java paratodos1Java paratodos1
Java paratodos1
 
JPA en Netbeans
JPA en NetbeansJPA en Netbeans
JPA en Netbeans
 
Curso de Desarrollo Web 2
Curso de Desarrollo Web 2Curso de Desarrollo Web 2
Curso de Desarrollo Web 2
 
PHP - MYSQL
PHP - MYSQLPHP - MYSQL
PHP - MYSQL
 
Introducción a Java Persistence API
Introducción a Java Persistence APIIntroducción a Java Persistence API
Introducción a Java Persistence API
 

Reportes Jasper sin BBDD

  • 1. REPORTES JASPERREPORT E IREPORT SIN CONEXIÓN A UNA BBDD En este post vamos a ver como se pasan parámetros desde java al reporte sin necesidad de una conexión a una BBDD, es decir, podemos pasar los parámetros que queramos. Vamos a comenzar creando un proyecto nuevo (File/New Project) y una clase en java que utilizaremos para instanciar objetos ( botón derecho en el paquete y New/java Class) y así pasar los datos al datasource. Para usar de ejemplo, hemos creado la clase Asistentes. public class Asistentes { private Integer id; private String nombre; private String apellidos; private String dni; public Asistentes(){ } public Asistentes(int id, String nombre, String apellidos, String dni) { this.id = id; this.nombre = nombre; this.apellidos = apellidos; this.dni = dni; } public int getId() { return id; } public void setId(Integer id) { this.id = id;
  • 2. } public String getApellidos() { return apellidos; } public void setApellidos(String apellidos) { this.apellidos = apellidos; } public String getDni() { return dni; } public void setDni(String dni) { this.dni = dni; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } } Esta clase tiene cuatro atributos, constructor por defecto y constructor parametrizado. También debemos incluir los getters and setters ya que los atributos son privados y necesitaremos asignar esos valores. A continuación vamos a crear el reporte. Para ello botón derecho en el paquete y nuevo Empty report.
  • 3.
  • 4. Para editar el reporte vamos a utilizar el programa de para netbeans). Os lo podéis descargar del siguiente enlace: http://sourceforge.net/projects/ireport/files/iReport/ En nuestro reporte vamos a asignar etiquetas para las columnas y para el nombre del reporte. Esto se hace con derecha). Para editar el reporte vamos a utilizar el programa de iReport, que previamente lo tenemos que tener instalado ( a parte del plugin de iReport para netbeans). Os lo podéis descargar del siguiente enlace: http://sourceforge.net/projects/ireport/files/iReport/ En nuestro reporte vamos a asignar etiquetas para las columnas y para el nombre del reporte. Esto se hace con , que previamente lo tenemos que tener instalado ( a parte del plugin de iReport En nuestro reporte vamos a asignar etiquetas para las columnas y para el nombre del reporte. Esto se hace con Static Text (Paleta que está a la
  • 5. Para asignar los valores que van a ir rellenando las diferentes columnas tenemos que crear unas variables y unos campos. Estos campos se crean pinchando botón derecho en Fields/Agregar Field. Hay que asignarles el tipo de dato (java.lang.String, java.lang.Integer o el que sea), y debe de coincidir con el tipo de dato que le pasemos en el programa principal, en este caso con el tipo de datos de las variables de nuestra clase Asistentes.
  • 6. Una vez creados todos, pinchamos y los arrastramos al reporte. Así quedaría el nuestro: Muy bien, ahora hay que crear la clase para pasar estos datos. Esta clase tiene que implementar la clase JRDataSource, y tiene dos métodos que son obligatorios sobreescribir, el método next() y getFieldValue(JRField jrf). En el método next incrementará el contador y JasperReport sabrá cuantos Asistentes van a existir. El método getFieldValue asignará los valores a los Fields correspondientes. A parte en esta clase vamos a crear una variable que será una lista de Asistentes y también un método para ir agregando cada asistente a la lista. La clase quedaría así: public class AsistentesDataSource implements JRDataSource{ private List<Asistentes> listaAsistentes = new ArrayList<Asistentes>(); private int indiceParticipanteActual = -1;
  • 7. @Override public boolean next() throws JRException { return ++indiceParticipanteActual < listaAsistentes.size(); } public void addAsistente(Asistentes Asistente){ this.listaAsistentes.add(Asistente); } @Override public Object getFieldValue(JRField jrf) throws JRException { Object valor = null; if ("id".equals(jrf.getName())){ valor = listaAsistentes.get(indiceParticipanteActual).getId(); } else if ("nombre".equals(jrf.getName())){ valor = listaAsistentes.get(indiceParticipanteActual).getNombre(); } else if ("apellidos".equals(jrf.getName())){ valor = listaAsistentes.get(indiceParticipanteActual).getApellidos(); } else if ("dni".equals(jrf.getName())){ valor = listaAsistentes.get(indiceParticipanteActual).getDni(); } return valor; } }
  • 8. En el main() tenemos que inicializar jasperreport y la clase Asistentes. También crear los objetos y pasarlos al datasource además de crear el reporte. El método main() quedaría de la siguiente forma: public static void main(String[] args) { // TODO code application logic here InputStream inputStream = null; JasperPrint jasperPrint= null; AsistentesDataSource datasource = new AsistentesDataSource(); for(int i = 0; i<=5; i++){ Asistentes asist; asist = new Asistentes(i, "AsistenteNombre de "+i,"AsistenteApellidos de "+i, "Asistente dni de "+i); datasource.addAsistente(asist); } try { inputStream = new FileInputStream ("src/reportes/reporte01.jrxml"); } catch (FileNotFoundException ex) { JOptionPane.showMessageDialog(null,"Error al leer el fichero de carga jasper report "+ex.getMessage()); } try{ JasperDesign jasperDesign = JRXmlLoader.load(inputStream); JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);
  • 9. jasperPrint = JasperFillManager.fillReport(jasperReport, null, datasource); JasperExportManager.exportReportToPdfFile(jasperPrint, "src/reportes/reporte01.pdf"); }catch (JRException e){ JOptionPane.showMessageDialog(null,"Error al cargar fichero jrml jasper report "+e.getMessage()); } } Ejecutamos el proyecto ya tenemos nuestro reporte: Hay problemas con la versión de iReport y Windows. Al ejecutar el proyecto nos puede aparecer dos tipos de errores. • Error uuid: no está permitido que el atributo uuid aparezca en el elemento jasperreport • Error cast: can not cast from Integer to String.
  • 10.
  • 11. Para el error del uuid simplemente en la vista del xml del reporte hay que borrar todos los campos donde venga el uuid. Para el error del cast, hay que añadir en los <textFieldExpressions> la clase correspondiente (String, Integer,Float,...) Podéis descargaros el proyecto en GitHub -> https://github.com/sandritascs/ReporteJasperReport BLOG: http://sandritascs.blogspot.com.es/2015/01/reportes-con-jasperreports-e-ireport.html