Mi primer reporte en java con Eclipse e ireport Mysql

En este pequeño tutorial o ejemplo crearemos un reporte usando la IDE Eclipse junto con ireport , y visualizaremos nuestro reporte en pantalla y lo exportaremos en PDF.

Tambien te Puede interesar: Reportes en java con JasperReports e iReports - Netbeans
Empezaremos abriendo nuestro editor eclipse JUNO que  fue el que utilice para crear este pequeño ejemplo, Primiero nos vamos a File --> Java Project
En Project Name Le ponemos el nombre a nuestro proyecto en mi caso le puse reportesEclipse le damos en finish y listo.

Despues de hacer este paso debemos descargar la ultima version del programa  Ireport y las librerias jasperreport.
Descargar:
Ireport Designer
JasperReports Library

Luego de descargados nos vamos a Ireport y empezamos a diseñar nuestro nuestro reporte

CREACION DEL REPORTE

Abrimos irreport y lo primero que haremos es crear un Datasource pero como lo creamos pues fácil
aquí una imagen ilustrativa le damos clic
datasource

Luego Clic en New Luego

Jdbc Connection
Le damos en Next y configuramos nuestra conexión

Configuración conexión Ireport

Cuando hagamos esto le damos en test para probar que todo ha salido Bien luego en Save.
creamos un nuevo reporte AsistenciaCapacitaciones dentro de un nuevo paquete llamado reportes
Elementos ireport




creacion del reporte





Consulta para el reporte


select * from empleado ;









Asi quedaría el reporte


vista del reporte

Probamos el reporte


vista del reporte

Este es el codigo fuente del archivo 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="report name" pageWidth="595" pageHeight="842" columnWidth="535" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20">
    <property name="ireport.zoom" value="1.0"/>
    <property name="ireport.x" value="0"/>
    <property name="ireport.y" value="0"/>
    <queryString>
        <![CDATA[select * from empleado]]>
    </queryString>
    <field name="emp_id" class="java.lang.Integer"/>
    <field name="emp_nom" class="java.lang.String"/>
    <field name="emp_ape" class="java.lang.String"/>
    <field name="emp_car" class="java.lang.String"/>
    <field name="emp_dep_id" class="java.lang.Integer"/>
    <background>
        <band splitType="Stretch"/>
    </background>
    <title>
        <band height="79" splitType="Stretch">
            <staticText>
                <reportElement x="0" y="25" width="555" height="29"/>
                <textElement textAlignment="Center">
                    <font fontName="Arial" size="18"/>
                </textElement>
                <text><![CDATA[Empleados de la capacitacion]]></text>
            </staticText>
        </band>
    </title>
    <pageHeader>
        <band splitType="Stretch"/>
    </pageHeader>
    <columnHeader>
        <band height="40" splitType="Stretch">
            <staticText>
                <reportElement x="0" y="0" width="100" height="20"/>
                <textElement/>
                <text><![CDATA[emp_id]]></text>
            </staticText>
            <staticText>
                <reportElement x="128" y="0" width="100" height="20"/>
                <textElement/>
                <text><![CDATA[emp_nom]]></text>
            </staticText>
            <staticText>
                <reportElement x="265" y="1" width="100" height="20"/>
                <textElement/>
                <text><![CDATA[emp_car]]></text>
            </staticText>
        </band>
    </columnHeader>
    <detail>
        <band height="33" splitType="Stretch">
            <textField>
                <reportElement x="0" y="0" width="100" height="20"/>
                <textElement/>
                <textFieldExpression class="java.lang.Integer"><![CDATA[$F{emp_id}]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement x="128" y="0" width="100" height="20"/>
                <textElement/>
                <textFieldExpression class="java.lang.String"><![CDATA[$F{emp_nom}]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement x="265" y="0" width="100" height="20"/>
                <textElement/>
                <textFieldExpression class="java.lang.String"><![CDATA[$F{emp_car}]]></textFieldExpression>
            </textField>
        </band>
    </detail>
    <columnFooter>
        <band splitType="Stretch"/>
    </columnFooter>
    <pageFooter>
        <band splitType="Stretch"/>
    </pageFooter>
    <summary>
        <band splitType="Stretch"/>
    </summary>
</jasperReport>


El reporte lo vamos a guardar en un paquete llamado reportes

Cuando ya terminemos nuestro diseño en ireport Nos vamos a eclipse Clic izquierdo en el Proyecto
Properties->Java Build Path-> Add External Jars y empezamos agregar los . jar necesarios para la creación del reporte desde java.
Los jar necesarios son:

barbecue.jar
barcode4j.jar
commons-beanutils.jar
commons-collections.jar
commons-digester.jar
commons-javaflow.jar
commons-logging.jar
groovy-all.jar
iText.jar
jasperreports.jar
jasperreports-applet.jar
jasperreports-fonts.jar
jasperreports-javaflow.jar
jcommon.jar
jdt-compiler.jar
jfreechart.jar
log4j.jar
mondrian.jar
png-encoder.jar
poi.jar
rhino.jar
servlet.jar
xalan.jar

Ademas también debes descargar el driver JDBC de mysql-conector



Luego creamos un paquete llamado utilidades y dentro de le una clase llamada Reportes:

La cual contiene los siguientes métodos:


package utilidades;

//import com.lowagie.text.pdf.PdfWriter;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.Serializable;
import java.sql.Connection;
import java.util.Locale;
import java.util.Map;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporter;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.export.JRPdfExporter;
import net.sf.jasperreports.engine.export.JRPdfExporterParameter;
import net.sf.jasperreports.engine.export.JRXlsAbstractExporterParameter;
import net.sf.jasperreports.engine.export.JRXlsExporter;
import net.sf.jasperreports.engine.export.JRXlsExporterParameter;
import net.sf.jasperreports.engine.util.JRSaver;
import net.sf.jasperreports.view.JasperViewer;

public class Reportes implements Serializable{
private  JasperReport reporte;
private JasperPrint print;
//exportar reporte a axcel
   public void reporteExcelImpresion(InputStream rutaJrxml,String rutaArchivoXLS,Map<String, Object> parametros,Connection conexion) throws JRException, FileNotFoundException{
    this.reporte=JasperCompileManager.compileReport(rutaJrxml);
    //luego ponemos los parametros que necesitamos:
    print = JasperFillManager.fillReport(this.reporte, parametros, conexion);
    JRXlsExporter exportador = new JRXlsExporter();
    exportador.setParameter(JRExporterParameter.JASPER_PRINT,print);
    exportador.setParameter(JRExporterParameter.OUTPUT_FILE_NAME,rutaArchivoXLS);
    exportador.setParameter(JRExporterParameter.IGNORE_PAGE_MARGINS,true);
    exportador.setParameter(JRXlsAbstractExporterParameter.IS_WHITE_PAGE_BACKGROUND, false);
    exportador.setParameter(JRXlsAbstractExporterParameter.IS_IGNORE_CELL_BORDER,false);
    exportador.setParameter(JRXlsAbstractExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_COLUMNS,true);
    exportador.setParameter(JRXlsExporterParameter.IS_DETECT_CELL_TYPE ,true);
    exportador.setParameter(JRXlsExporterParameter.IS_FONT_SIZE_FIX_ENABLED,true);
    exportador.exportReport();
}
   //metodo para generar el reporte en pdf si que se puedan copiar las imagenes ni el texto
public boolean  jasperReport(String ruta, InputStream dataSourceName, Map<String, Object> params,Connection conn) throws ClassNotFoundException, JRException {
        this.reporte=JasperCompileManager.compileReport(dataSourceName);
       
        this.print = JasperFillManager.fillReport(this.reporte, params, conn);
       if(this.print.getPages().isEmpty()){
       return false;
       }
        //int permisos =PdfWriter.ALLOW_PRINTING;
        //Esta clase es la encargada de exportar el archivo a pdf
        final JRExporter jtrtf= new JRPdfExporter();

        jtrtf.setParameter(JRPdfExporterParameter.IS_ENCRYPTED, Boolean.TRUE);
        jtrtf.setParameter(JRPdfExporterParameter.IS_128_BIT_KEY, Boolean.TRUE);
        //jtrtf.setParameter(JRPdfExporterParameter.PERMISSIONS, permisos);
        jtrtf.setParameter(JRExporterParameter.JASPER_PRINT, this.print); 
        //Gurdamos una copia en el computador Ejemplo c:/reportes.jrprint
        JRSaver.saveObject(this.print,ruta+".jrprint");
         //Gurdamos una copia en el computador Ejemplo c:/reportes.pdf
       jtrtf.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, ruta+".pdf");
       //este metodo exporta a los diferentes formatos en este caso pdf
        jtrtf.exportReport();
        //Metodo que se encarga de mostrar el reporte en la pantalla
       JasperViewer.viewReport(this.print,false,Locale.getDefault());
    return true;
}

    
}

Esta es la clase encargada de realizar la conexión
package utilidades;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 *
 * @author jesus cabarcas
 */
 /*Creamos la clase */
public class Conexion {
    private Connection conexion; // Abstrae una conexion a la base de datos
     private String usuario = "root"; // usuario con permisos para conectarse a Base de datos
    private String password = "123456"; // contraseña del usuario que se puede conectar a la base de datos
    private String driver = "com.mysql.jdbc.Driver"; // Clase del Driver de jConnector
    private String beseDatos="jdbc:mysql://localhost:3306/capacitaciones";//cadena de coneccion
    private static Conexion instancia;
    /** Crea a new instancia de  Conexion */
    public static Conexion getInstancia (){
    if(Conexion.instancia==null){
    Conexion.instancia=new Conexion();
    }
    return instancia;
    }
    
   /** Metodo que se encarga de conectar a la base de datos*/
    public void conectar()throws Exception {
     //si la conecion es null nos conectamos
        if(this.getConexion()!=null){
            return;
        }
        else if(this.getConexion() == null){


            try {
                Class.forName(this.getDriver()) ; // obtine una istancia de la clase Diver
// establece la conexion con el Diver jconector y este a su vez con la base de datos
                this.setConexion(DriverManager.getConnection(this.getBeseDatos(), this.getUsuario(), this.getPassword()));
              
            } catch (SQLException ex) {
              throw new Exception("ERROR AL CONECTARCE CON LA BASE DE DATOS");
            } catch (ClassNotFoundException ex) {
                 throw new Exception("Clase no encontrada");
            }
  }


    }
    /** desconecta de la base de datos */
    public void desconectar()throws Exception{
    if(this.getConexion()==null)
        this.setConexion(null);

    }

    public Conexion() {
    }
/*Metodos getter y setter*/
    public Connection getConexion() {
        return conexion;
    }

    public void setConexion(Connection conexion) {
        this.conexion = conexion;
    }

    public String getUsuario() {
        return usuario;
    }

    public void setUsuario(String usuario) {
        this.usuario = usuario;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getDriver() {
        return driver;
    }

    public void setDriver(String driver) {
        this.driver = driver;
    }

    public String getBeseDatos() {
        return beseDatos;
    }

    public void setBeseDatos(String beseDatos) {
        this.beseDatos = beseDatos;
    }

}


Este es el método principal donde se generara el reporte


package capacitacion;


import java.sql.SQLException;
import java.util.HashMap;
import utilidades.Conexion;
import utilidades.Reportes;
import org.apache.log4j.BasicConfigurator;
public class Capacitacion { public static void main(String[] args) throws SQLException { BasicConfigurator.configure();  
 // Creamos un objeto de la clase conexion
      
     Reportes reporte= new Reportes();
        try {
             // llamamos al metodo get conection que nos devuelve un Objeto connection
             
                 HashMap<String, Object> mp= new HashMap<String, Object>();
            // Lo exporta a pdf y lo muestra en la pantalla
             Conexion.getInstancia().conectar();
    reporte.jasperReport("D:/reportes.pdf",
            Capacitacion.class.getResourceAsStream("/reportes/AsistenciaCapacitaciones.jrxml")
            , mp,
            Conexion.getInstancia().getConexion());
    Conexion.getInstancia().desconectar();
  
   
   // Lamamos el metodo para conectarnos a la base de datos       
    Conexion.getInstancia().conectar();
    // Llamamos el metodo que exporta a excel y lo guar en el pc en mi caso en E
    reporte.reporteExcelImpresion(
            Capacitacion.class.getResourceAsStream("/reportes/AsistenciaCapacitaciones.jrxml")
            ,"D:/reportes.xls"
            ,mp,
            Conexion.getInstancia().getConexion());
    // Soltamos la conexion
    Conexion.getInstancia().desconectar();
        } catch (Exception ex) {
            System.out.print(ex.toString());
        }finally{
             try {
                 Conexion.getInstancia().desconectar();
            } catch (Exception e) {

                System.out.print(e.toString());
            }
        }
    }
}


Query para la creacion de la base de datos


CREATE SCHEMA IF NOT EXISTS `capacitaciones` DEFAULT CHARACTER SET latin1 ;
USE `capacitaciones` ;

-- -----------------------------------------------------
-- Table `capacitaciones`.`asistencia`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `capacitaciones`.`asistencia` (
`asi_id` INT(11) NOT NULL AUTO_INCREMENT ,
`asi_cap_id` INT(11) NOT NULL ,
`asi_emp_id` INT(11) NOT NULL ,
PRIMARY KEY (`asi_id`) ,
INDEX `cap_id` (`asi_cap_id` ASC) ,
INDEX `emp_id` (`asi_emp_id` ASC) )
ENGINE = InnoDB
AUTO_INCREMENT = 4
DEFAULT CHARACTER SET = latin1;


-- -----------------------------------------------------
-- Table `capacitaciones`.`entidad`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `capacitaciones`.`entidad` (
`ent_id` INT(11) NOT NULL AUTO_INCREMENT ,
`ent_des` VARCHAR(130) NOT NULL ,
`ent_tip` INT(11) NULL DEFAULT NULL ,
PRIMARY KEY (`ent_id`) )
ENGINE = InnoDB
AUTO_INCREMENT = 2
DEFAULT CHARACTER SET = latin1;


-- -----------------------------------------------------
-- Table `capacitaciones`.`estado`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `capacitaciones`.`estado` (
`est_id` INT(11) NOT NULL AUTO_INCREMENT ,
`est_des` VARCHAR(45) NULL DEFAULT NULL ,
PRIMARY KEY (`est_id`) )
ENGINE = InnoDB
AUTO_INCREMENT = 2
DEFAULT CHARACTER SET = latin1;


-- -----------------------------------------------------
-- Table `capacitaciones`.`capacitacion`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `capacitaciones`.`capacitacion` (
`cap_id` INT(11) NOT NULL AUTO_INCREMENT ,
`cap_tem` VARCHAR(255) NULL DEFAULT NULL ,
`cap_fecIni` DATETIME NOT NULL ,
`cap_fecFin` DATETIME NOT NULL ,
`cap_obs` VARCHAR(255) NULL DEFAULT NULL ,
`cap_fecReg` DATETIME NOT NULL ,
`cap_dir` VARCHAR(255) NULL DEFAULT NULL ,
`cap_est_id` INT(11) NOT NULL ,
`cap_ent_id` INT(11) NOT NULL ,
PRIMARY KEY (`cap_id`) ,
INDEX `cap_ent_id` (`cap_ent_id` ASC) ,
INDEX `cap_est_id` (`cap_est_id` ASC) ,
CONSTRAINT `cap_ent_id`
FOREIGN KEY (`cap_ent_id` )
REFERENCES `capacitaciones`.`entidad` (`ent_id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `cap_est_id`
FOREIGN KEY (`cap_est_id` )
REFERENCES `capacitaciones`.`estado` (`est_id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
AUTO_INCREMENT = 6
DEFAULT CHARACTER SET = latin1;


-- -----------------------------------------------------
-- Table `capacitaciones`.`dependencia`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `capacitaciones`.`dependencia` (
`dep_id` INT(11) NOT NULL AUTO_INCREMENT ,
`dep_des` VARCHAR(255) NOT NULL ,
PRIMARY KEY (`dep_id`) )
ENGINE = InnoDB
DEFAULT CHARACTER SET = latin1;


-- -----------------------------------------------------
-- Table `capacitaciones`.`empleado`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `capacitaciones`.`empleado` (
`emp_id` INT(11) NOT NULL ,
`emp_nom` VARCHAR(60) NOT NULL ,
`emp_ape` VARCHAR(60) NOT NULL ,
`emp_car` VARCHAR(120) NOT NULL ,
`emp_dep_id` INT(11) NOT NULL ,
PRIMARY KEY (`emp_id`) ,
INDEX `dep_id` (`emp_dep_id` ASC) ,
CONSTRAINT `dep_id`
FOREIGN KEY (`emp_dep_id` )
REFERENCES `capacitaciones`.`dependencia` (`dep_id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = latin1;

Luego insertamos estos dos empleados para ver el resultado
INSERT
 INTO `dependencia` (`dep_id`, `dep_des`) VALUES (1, 'Sistemas');

INSERT INTO `empleado` (`emp_id`, `emp_nom`, `emp_ape`, `emp_car`, `emp_dep_id`) VALUES
(73222566, 'juan pablo', 'morales', 'Jefe de sistemas', 1),
(75532012, 'carlo', 'Martinez', 'Auxiliar de Sistemas', 1);


Mi primer Reporte en Ireport usando Java , Maven y NetBeans Generar PDF Versión WEB

Mi primer Reporte en Ireport usando Java , Maven y NetBeans Generar PDF Versión WEB Estructura del proyecto Listado de rutas de car...