Problem placing multiple data from a list in a report

Asked

Viewed 1,357 times

7

Good morning guys, this is a somewhat complicated question to explain, so I will do my best to make the question clear.

I have a list <UnimedLote>. In this list I have several data, among these data I want to list more than once, for example. A Beneficiary may have several procedures, so each time I generated the report he listed the procedures within that beneficiary in such a way: inserir a descrição da imagem aqui

Note the Completion Date, Service Description... The data is listed within the Beneficiary.

I can list all the data, but it always repeats the name of the Beneficiary, and does not list the procedures within it. I can do this: inserir a descrição da imagem aqui

Notice that I can list all but separate ones. Can anyone help me figure out where I have to put them? Follows code:

for (List<UnimedGuia> lst : listaAuxiliar) {

        System.out.println("Numero do rel: " + nRel);
        System.out.println("Nome do Arquivo: " + nomeArquivo1);

        String nomePrestador = lista1.get(nRel).getNomePrestador();
        String[] as = nomePrestador.split("/");
        nomePrestador = as[0];

        filtro = new HashMap<>();

        filtro.put("Registro ANS", lista1.get(nRel).getRegistroANS());
        filtro.put("Nome da Operadora", lista1.get(nRel).getNomeOperadora());
        filtro.put("CNPJ Operadora", lista1.get(nRel).getCnpjOperadora());
        filtro.put("Nr. Demonstrativo", lista1.get(nRel).getNumeroDemonstrativo());
        filtro.put("Data Emissao Demonstrativo", lista1.get(nRel).getDataEmissaoDemonstrativo());
        filtro.put("Data Competencia", lista1.get(nRel).getDataCompetencia());
        filtro.put("CodPrestador", lista1.get(nRel).getCodigoPrestador());
        filtro.put("NomePrestador", lista1.get(nRel).getNomePrestador());
        filtro.put("CNES", lista1.get(nRel).getCodigoCNES());
        filtro.put("NumLote", lista.get(nRel).getNumeroLote());
        filtro.put("DataEnvioLote", lista.get(nRel).getDataEnvioLote());
        filtro.put("NumProtocolo", lista.get(nRel).getNumeroProtocolo());

        filtro.put("ValorProtocolo", lista1.get(nRel).getValorLiberadoGeral());
        filtro.put("ValorProcessadoGeral", lista1.get(nRel).getValorProcessadoGeral());
        filtro.put("ValorGlosaGeral", lista1.get(nRel).getValorGlosaGeral());
        filtro.put("ValorLiberadoGeral", lista1.get(nRel).getValorLiberadoGeral());

        codArquivoPrestador = lista1.get(nRel).getCodigoPrestador();
        relatorio = gerarRelatorio(lst, nRel, nomePrestador, dataSistema);

}

Some data is passed by parameters to the report, as it is data that is not repeated, such as header, company name, etc. Method generating the report:

public boolean gerarRelatorio(List list, int numeroRelatorio,
            String nomePrestador, String dataSistema) {

        JasperReport report = null;
        InputStream image = this.getClass().getResourceAsStream(
                "/br/com/xml/relatorio/LOGO.png");
        filtro.put("Image", image);

        try {
            InputStream inputStreamReal = getClass().getResourceAsStream(
                    "/br/com/xml/relatorio/Relatorio2.jrxml");
            report = JasperCompileManager.compileReport(inputStreamReal);

        } catch (JRException ex) {
            Logger.getLogger(frmPegaXml.class.getName()).log(Level.SEVERE,
                    null, ex);
            JOptionPane.showMessageDialog(null, "Erro ao pegar arquivos!",
                    "ERRO!", JOptionPane.ERROR_MESSAGE);
        }

        try {
            JasperPrint print = JasperFillManager.fillReport(report, filtro,
                    new JRBeanCollectionDataSource(list));
            JasperExportManager.exportReportToPdfFile(print,
                    "C:/Demonstrativos/" + dataSistema + "/" + nomePrestador
                            + "_" + dataSistema + "_" + numeroRelatorio
                            + ".pdf");

            /* Variaveis necessarias para salvar o Arquivo */
            caminho1 = "C:/Demonstrativos/" + dataSistema + "/";
            ext = ".zip";
            nomeArquivo1 = nomePrestador + "_" + dataSistema + "_"
                    + numeroRelatorio;
            caminhoCompleto = caminho1 + nomeArquivo1 + ".pdf";

            codAP = Long.parseLong(codArquivoPrestador);
            // salvarArquivos(caminhoRar, ext, nomeArquivo1, codAP);
            relatoriosGerados = numeroRelatorio + 1;

            return true;

            /* Variaveis necessarias para salvar o Arquivo */
        } catch (JRException ex) {
            Logger.getLogger(frmPegaXml.class.getName()).log(Level.SEVERE,
                    null, ex);
            JOptionPane
                    .showMessageDialog(
                            null,
                            "Erro ao Gerar relatório, verifique se nenhum arquivo está aberto ou se o nome está correto!\n"
                                    + ex, "ERRO!", JOptionPane.ERROR_MESSAGE);
            return false;
        }

    }

Anyone can help?


Band Detail - Jrxml file:

inserir a descrição da imagem aqui


Method filling the list with data:

public List<Procedimentos> realizaLeituraXML(String arquivoXML) throws ParserConfigurationException, SAXException, IOException {
        //fazer o parse do arquivo e criar o documento XML
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(arquivoXML);

        Element elem = doc.getDocumentElement();
        NodeList tagdadosLote = elem.getElementsByTagName("unimed:dadosLote");

        List<Procedimentos> listaLote = new ArrayList<>();
        System.out.printf("\n tagdadosLote %s ", tagdadosLote.getLength());
        for (int i = 0; i < tagdadosLote.getLength(); i++) {
            NumeroLote n = new NumeroLote();
            String lote = "";

            Element elementoLote = (Element) tagdadosLote.item(i);
            lote = pegaTag(elementoLote, "unimed:numeroLote");

            NodeList tagGuia = (NodeList) elementoLote.getElementsByTagName("unimed:guia");
            // Como sabemos pela estrutura que só tem 1 elemento não necessitamos de um for podendo fixar o indice.
            NodeList tagdadosGuia = ((Element) tagGuia.item(0)).getElementsByTagName("unimed:dadosGuia");

            for (int y = 0; y < tagdadosGuia.getLength(); y++) {

                Procedimentos contato = new Procedimentos();
                NodeList tagBeneficiario0 = ((Element) tagdadosGuia.item(y)).getElementsByTagName("unimed:beneficiario");
                NodeList tagProcedimentos = ((Element) tagdadosGuia.item(y)).getElementsByTagName("unimed:procedimentos");
                NodeList tagProcedimentos1 = ((Element) tagProcedimentos.item(0)).getElementsByTagName("unimed:dadosProcedimento");

                Element elementoBeneficiarioname = (Element) tagdadosGuia.item(y);
                String nomeBeneficiario = (pegaTag(elementoBeneficiarioname, "unimed:nomeBeneficiario"));
                contato.setNomeBeneficiario(nomeBeneficiario);

                for (int a = 0; a < tagProcedimentos1.getLength(); a++) {
                    NodeList tagProcedimento = ((Element) tagProcedimentos1.item(a)).getElementsByTagName("unimed:procedimento");

                    for (int b = 0; b < tagProcedimento.getLength(); b++) {
                        //Aqui é onde pego os demais dados Do arquivo XML e passo para meu objeto "contato"
                        //Deixei vazio pois é um metodo muito extenso

                        listaLote.add(contato);
                    }

                }

            }

        }

        //System.err.println("Lista lote: " + listaLote);
        return listaLote;

    }

1 answer

3


Taking a closer look, I identified 3 possible entities: Guide, Benefit, Procedure. Where 1 guide has 1 beneficiary and 1 beneficiary may contain N procedures.

Looking closely at the jrxml ...

This is an expected approximate result (you should adjust as you like later), I will explain some important points later. This answer assumes you already have the basic knowledge of Jasper Report.

resultado esperado

jrxml guide.

guia

beneficiario.jrxml

inserir a descrição da imagem aqui

jrxml procedure.

inserir a descrição da imagem aqui

Important points

The points I will mention here are not absolute truths, they are just important points that I have acquired with experience in different projects:

  • One jrxml per entity. Facilitates maintenance and here there can be reuse of blocks for more than one report.
  • Every time you go to access an object/association and notice that it is an information block exclusively of that object, preferably for sub-report (in your case, I used this approach in beneficiario.jrxml).
  • Need to iterate a list of objects that points to another list of objects ? Use sub-reports.
  • Do you need to print something right after a subreport (which usually has a dynamic size) using the same bandwidth and the data is being overwritten by the sub-report data ? Change the "Position Type" property to float.

How the sub-report call was made ?

In the properties tab of the sub-report component, there is a property called "Connection Type". Select "use Datasource Expression".

connection type

In Data Source Expression, put:

new net.sf.jasperreports.engine.data.JRBeanCollectionDataSource(/* expressão que resulte em um objeto que implemente java.util.Collection */)

Don’t forget also point to the . Jasper of the sub-report, changing the property "Subreport Expression".


jrxml sources

jrxml guide.

<?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="guia" pageWidth="595" pageHeight="842" columnWidth="555" 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"/>
    <parameter name="SUBREPORT_DIR" class="java.lang.String" isForPrompting="false">
        <defaultValueExpression><![CDATA["./"]]></defaultValueExpression>
    </parameter>
    <queryString>
        <![CDATA[]]>
    </queryString>
    <field name="codigoGlosa" class="java.lang.Integer">
        <fieldDescription><![CDATA[codigoGlosa]]></fieldDescription>
    </field>
    <field name="valorGlosa" class="java.math.BigDecimal">
        <fieldDescription><![CDATA[valorGlosa]]></fieldDescription>
    </field>
    <field name="valorLiberado" class="java.math.BigDecimal">
        <fieldDescription><![CDATA[valorLiberado]]></fieldDescription>
    </field>
    <field name="valorProcessado" class="java.math.BigDecimal">
        <fieldDescription><![CDATA[valorProcessado]]></fieldDescription>
    </field>
    <field name="beneficiario" class="com.stackoverflow.pt.model.Beneficiario">
        <fieldDescription><![CDATA[beneficiario]]></fieldDescription>
    </field>
    <background>
        <band splitType="Stretch"/>
    </background>
    <detail>
        <band height="144" splitType="Stretch">
            <subreport>
                <reportElement positionType="Float" x="0" y="30" width="555" height="30"/>
                <dataSourceExpression><![CDATA[new net.sf.jasperreports.engine.data.JRBeanCollectionDataSource(($F{beneficiario}.getProcedimentos()))]]></dataSourceExpression>
                <subreportExpression class="java.lang.String"><![CDATA[$P{SUBREPORT_DIR} + "procedimento.jasper"]]></subreportExpression>
            </subreport>
            <staticText>
                <reportElement positionType="Float" x="0" y="62" width="120" height="26"/>
                <textElement verticalAlignment="Middle">
                    <font isBold="true"/>
                </textElement>
                <text><![CDATA[Total da Guia:]]></text>
            </staticText>
            <staticText>
                <reportElement positionType="Float" x="37" y="88" width="120" height="26"/>
                <textElement textAlignment="Center" verticalAlignment="Middle">
                    <font size="8" isBold="true"/>
                </textElement>
                <text><![CDATA[Valor Processado Guia (R$)]]></text>
            </staticText>
            <staticText>
                <reportElement positionType="Float" x="157" y="88" width="120" height="26"/>
                <textElement textAlignment="Center" verticalAlignment="Middle">
                    <font size="8" isBold="true"/>
                </textElement>
                <text><![CDATA[Valor Liberado Guia (R$)]]></text>
            </staticText>
            <staticText>
                <reportElement positionType="Float" x="277" y="88" width="120" height="26"/>
                <textElement textAlignment="Center" verticalAlignment="Middle">
                    <font size="8" isBold="true"/>
                </textElement>
                <text><![CDATA[Valor Glosa Guia (R$)]]></text>
            </staticText>
            <staticText>
                <reportElement positionType="Float" x="397" y="88" width="120" height="26"/>
                <textElement textAlignment="Center" verticalAlignment="Middle">
                    <font size="8" isBold="true"/>
                </textElement>
                <text><![CDATA[Código Glosa Guia]]></text>
            </staticText>
            <textField>
                <reportElement positionType="Float" x="37" y="114" width="120" height="20"/>
                <textElement textAlignment="Center"/>
                <textFieldExpression class="java.math.BigDecimal"><![CDATA[$F{valorProcessado}]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement positionType="Float" x="157" y="114" width="120" height="20"/>
                <textElement textAlignment="Center"/>
                <textFieldExpression class="java.math.BigDecimal"><![CDATA[$F{valorLiberado}]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement positionType="Float" x="277" y="114" width="120" height="20"/>
                <textElement textAlignment="Center"/>
                <textFieldExpression class="java.math.BigDecimal"><![CDATA[$F{valorGlosa}]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement positionType="Float" x="397" y="114" width="120" height="20"/>
                <textElement textAlignment="Center"/>
                <textFieldExpression class="java.lang.Integer"><![CDATA[$F{codigoGlosa}]]></textFieldExpression>
            </textField>
            <line>
                <reportElement positionType="Float" x="0" y="60" width="555" height="2"/>
            </line>
            <subreport>
                <reportElement positionType="Float" x="0" y="0" width="555" height="30"/>
                <dataSourceExpression><![CDATA[new net.sf.jasperreports.engine.data.JRBeanCollectionDataSource(java.util.Arrays.asList($F{beneficiario}))]]></dataSourceExpression>
                <subreportExpression class="java.lang.String"><![CDATA[$P{SUBREPORT_DIR} + "beneficiario.jasper"]]></subreportExpression>
            </subreport>
        </band>
    </detail>
</jasperReport>

beneficiario.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="beneficiario" pageWidth="555" pageHeight="842" columnWidth="555" leftMargin="0" rightMargin="0" topMargin="0" bottomMargin="0">
    <property name="ireport.zoom" value="1.5"/>
    <property name="ireport.x" value="0"/>
    <property name="ireport.y" value="0"/>
    <queryString>
        <![CDATA[]]>
    </queryString>
    <field name="guia" class="java.lang.String">
        <fieldDescription><![CDATA[guia]]></fieldDescription>
    </field>
    <field name="identificador" class="java.lang.String">
        <fieldDescription><![CDATA[identificador]]></fieldDescription>
    </field>
    <field name="nome" class="java.lang.String">
        <fieldDescription><![CDATA[nome]]></fieldDescription>
    </field>
    <field name="procedimentos" class="java.util.List">
        <fieldDescription><![CDATA[procedimentos]]></fieldDescription>
    </field>
    <field name="senha" class="java.lang.String">
        <fieldDescription><![CDATA[senha]]></fieldDescription>
    </field>
    <background>
        <band splitType="Stretch"/>
    </background>
    <detail>
        <band height="52" splitType="Stretch">
            <textField>
                <reportElement x="120" y="0" width="189" height="26"/>
                <textElement verticalAlignment="Middle"/>
                <textFieldExpression class="java.lang.String"><![CDATA[$F{nome}]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement x="439" y="0" width="116" height="26"/>
                <textElement verticalAlignment="Middle"/>
                <textFieldExpression class="java.lang.String"><![CDATA[$F{identificador}]]></textFieldExpression>
            </textField>
            <staticText>
                <reportElement x="0" y="24" width="120" height="28"/>
                <textElement verticalAlignment="Middle">
                    <font isBold="true"/>
                </textElement>
                <text><![CDATA[Número da Guia/Senha:]]></text>
            </staticText>
            <line>
                <reportElement x="0" y="0" width="555" height="2"/>
            </line>
            <line>
                <reportElement x="0" y="24" width="555" height="2"/>
            </line>
            <textField>
                <reportElement x="120" y="24" width="189" height="28"/>
                <textElement verticalAlignment="Middle"/>
                <textFieldExpression class="java.lang.String"><![CDATA[$F{guia} + "/" + $F{senha}]]></textFieldExpression>
            </textField>
            <staticText>
                <reportElement x="0" y="0" width="120" height="26"/>
                <textElement verticalAlignment="Middle">
                    <font isBold="true"/>
                </textElement>
                <text><![CDATA[Nome do Beneficiário:]]></text>
            </staticText>
            <staticText>
                <reportElement x="309" y="0" width="130" height="26"/>
                <textElement verticalAlignment="Middle">
                    <font isBold="true"/>
                </textElement>
                <text><![CDATA[Identificador Beneficiário:]]></text>
            </staticText>
        </band>
    </detail>
</jasperReport>

jrxml procedure.

<?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="procedimento" pageWidth="555" pageHeight="802" columnWidth="555" leftMargin="0" rightMargin="0" topMargin="0" bottomMargin="0">
    <property name="ireport.zoom" value="4.0"/>
    <property name="ireport.x" value="0"/>
    <property name="ireport.y" value="0"/>
    <queryString>
        <![CDATA[]]>
    </queryString>
    <field name="codigoServico" class="java.lang.String">
        <fieldDescription><![CDATA[codigoServico]]></fieldDescription>
    </field>
    <field name="codigoTabela" class="java.lang.String">
        <fieldDescription><![CDATA[codigoTabela]]></fieldDescription>
    </field>
    <field name="dataRealizacao" class="java.util.Date">
        <fieldDescription><![CDATA[dataRealizacao]]></fieldDescription>
    </field>
    <field name="descricaoServico" class="java.lang.String">
        <fieldDescription><![CDATA[descricaoServico]]></fieldDescription>
    </field>
    <field name="quantidadeExecutada" class="java.lang.Integer">
        <fieldDescription><![CDATA[quantidadeExecutada]]></fieldDescription>
    </field>
    <field name="valorGlosa" class="java.math.BigDecimal">
        <fieldDescription><![CDATA[valorGlosa]]></fieldDescription>
    </field>
    <field name="valorLiberado" class="java.math.BigDecimal">
        <fieldDescription><![CDATA[valorLiberado]]></fieldDescription>
    </field>
    <field name="valorProcessado" class="java.math.BigDecimal">
        <fieldDescription><![CDATA[valorProcessado]]></fieldDescription>
    </field>
    <field name="codigoGlosa" class="java.lang.Integer">
        <fieldDescription><![CDATA[codigoGlosa]]></fieldDescription>
    </field>
    <background>
        <band splitType="Stretch"/>
    </background>
    <title>
        <band height="33" splitType="Stretch">
            <staticText>
                <reportElement x="0" y="0" width="69" height="32"/>
                <textElement textAlignment="Center" verticalAlignment="Middle">
                    <font isBold="true"/>
                </textElement>
                <text><![CDATA[Data Realização]]></text>
            </staticText>
            <staticText>
                <reportElement x="69" y="0" width="100" height="32"/>
                <textElement textAlignment="Center" verticalAlignment="Middle">
                    <font isBold="true"/>
                </textElement>
                <text><![CDATA[Descrição Serviço]]></text>
            </staticText>
            <staticText>
                <reportElement x="169" y="0" width="36" height="32"/>
                <textElement textAlignment="Center" verticalAlignment="Middle">
                    <font isBold="true"/>
                </textElement>
                <text><![CDATA[Cod Tab]]></text>
            </staticText>
            <staticText>
                <reportElement x="205" y="0" width="50" height="32"/>
                <textElement textAlignment="Center" verticalAlignment="Middle">
                    <font isBold="true"/>
                </textElement>
                <text><![CDATA[Cod Serviço]]></text>
            </staticText>
            <staticText>
                <reportElement x="255" y="0" width="60" height="32"/>
                <textElement textAlignment="Center" verticalAlignment="Middle">
                    <font isBold="true"/>
                </textElement>
                <text><![CDATA[Qtde Exec]]></text>
            </staticText>
            <staticText>
                <reportElement x="315" y="0" width="60" height="32"/>
                <textElement textAlignment="Center" verticalAlignment="Middle">
                    <font isBold="true"/>
                </textElement>
                <text><![CDATA[Valor Processado]]></text>
            </staticText>
            <staticText>
                <reportElement x="375" y="0" width="60" height="32"/>
                <textElement textAlignment="Center" verticalAlignment="Middle">
                    <font isBold="true"/>
                </textElement>
                <text><![CDATA[Valor Liberado]]></text>
            </staticText>
            <staticText>
                <reportElement x="435" y="0" width="60" height="32"/>
                <textElement textAlignment="Center" verticalAlignment="Middle">
                    <font isBold="true"/>
                </textElement>
                <text><![CDATA[Valor Glosa]]></text>
            </staticText>
            <staticText>
                <reportElement x="495" y="0" width="60" height="32"/>
                <textElement textAlignment="Center" verticalAlignment="Middle">
                    <font isBold="true"/>
                </textElement>
                <text><![CDATA[Cod Glosa]]></text>
            </staticText>
            <line>
                <reportElement x="0" y="32" width="555" height="1"/>
            </line>
        </band>
    </title>
    <detail>
        <band height="21" splitType="Stretch">
            <textField isStretchWithOverflow="true" pattern="dd-MM-yyyy" isBlankWhenNull="true">
                <reportElement stretchType="RelativeToTallestObject" x="0" y="1" width="69" height="20"/>
                <textElement textAlignment="Center" verticalAlignment="Middle"/>
                <textFieldExpression class="java.util.Date"><![CDATA[$F{dataRealizacao}]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement x="69" y="1" width="100" height="20"/>
                <textElement textAlignment="Center" verticalAlignment="Middle"/>
                <textFieldExpression class="java.lang.String"><![CDATA[$F{descricaoServico}]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement x="169" y="1" width="36" height="20"/>
                <textElement textAlignment="Center" verticalAlignment="Middle"/>
                <textFieldExpression class="java.lang.String"><![CDATA[$F{codigoTabela}]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement x="205" y="1" width="50" height="20"/>
                <textElement textAlignment="Center" verticalAlignment="Middle"/>
                <textFieldExpression class="java.lang.String"><![CDATA[$F{codigoServico}]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement x="255" y="1" width="60" height="20"/>
                <textElement textAlignment="Center" verticalAlignment="Middle"/>
                <textFieldExpression class="java.lang.Integer"><![CDATA[$F{quantidadeExecutada}]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement x="315" y="1" width="60" height="20"/>
                <textElement textAlignment="Center" verticalAlignment="Middle"/>
                <textFieldExpression class="java.math.BigDecimal"><![CDATA[$F{valorProcessado}]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement x="375" y="1" width="60" height="20"/>
                <textElement textAlignment="Center" verticalAlignment="Middle"/>
                <textFieldExpression class="java.math.BigDecimal"><![CDATA[$F{valorLiberado}]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement x="435" y="1" width="60" height="20"/>
                <textElement textAlignment="Center" verticalAlignment="Middle"/>
                <textFieldExpression class="java.math.BigDecimal"><![CDATA[$F{valorGlosa}]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement x="495" y="1" width="60" height="20"/>
                <textElement textAlignment="Center" verticalAlignment="Middle"/>
                <textFieldExpression class="java.lang.Integer"><![CDATA[$F{codigoGlosa}]]></textFieldExpression>
            </textField>
        </band>
    </detail>
</jasperReport>

Java fonts

Class that executes the example

Main java.

package com.stackoverflow.pt;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.swing.JFrame;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.view.JasperViewer;

import com.stackoverflow.pt.model.Beneficiario;
import com.stackoverflow.pt.model.Guia;
import com.stackoverflow.pt.model.Procedimento;

public class Main {

    public static void main(String[] args) throws JRException {

        List<Guia> guias = Arrays.asList(newGuia(4));

        JasperPrint jasperPrint = JasperFillManager.fillReport(Main.class.getResourceAsStream("/guia.jasper"), new HashMap<String, Object>(), new JRBeanCollectionDataSource(guias));

        JasperViewer jasperViewer = new JasperViewer(jasperPrint);
        jasperViewer.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jasperViewer.setVisible(true);
    }

    private static Guia newGuia(int numero) {
        Guia guia = new Guia();
        guia.setBeneficiario(newBeneficiario(numero));
        guia.setCodigoGlosa(numero);
        guia.setValorGlosa(somaValorGlosa(guia.getBeneficiario().getProcedimentos()));
        guia.setValorLiberado(somaValorLiberado(guia.getBeneficiario().getProcedimentos()));
        guia.setValorProcessado(somaValorProcessado(guia.getBeneficiario().getProcedimentos()));
        return guia;
    }

    private static BigDecimal somaValorProcessado(List<Procedimento> procedimentos) {
        BigDecimal bigDecimal = new BigDecimal(0).setScale(2);
        for (Procedimento procedimento : procedimentos) {
            bigDecimal = bigDecimal.add(procedimento.getValorProcessado());
        }
        return bigDecimal;
    }

    private static BigDecimal somaValorLiberado(List<Procedimento> procedimentos) {
        BigDecimal bigDecimal = new BigDecimal(0).setScale(2);
        for (Procedimento procedimento : procedimentos) {
            bigDecimal = bigDecimal.add(procedimento.getValorLiberado());
        }
        return bigDecimal;
    }

    private static BigDecimal somaValorGlosa(List<Procedimento> procedimentos) {
        BigDecimal bigDecimal = new BigDecimal(0).setScale(2);
        for (Procedimento procedimento : procedimentos) {
            bigDecimal = bigDecimal.add(procedimento.getValorGlosa());
        }
        return bigDecimal;
    }

    private static Beneficiario newBeneficiario(int numero) {
        Beneficiario beneficiario = new Beneficiario();
        beneficiario.getProcedimentos().addAll(newProcedimento(numero));
        beneficiario.setGuia(String.valueOf(numero));
        beneficiario.setSenha(String.valueOf(numero) + String.valueOf(numero));
        beneficiario.setNome("Nome " + numero);
        beneficiario.setIdentificador(String.valueOf(numero));
        return beneficiario;
    }

    private static List<Procedimento> newProcedimento(int numero) {
        List<Procedimento> procedimentos = new ArrayList<Procedimento>();
        for (int x = 0; x < numero; x++) {
            Procedimento procedimento = new Procedimento();
            procedimento.setCodigoGlosa(x);
            procedimento.setCodigoServico("Servico " + x);
            procedimento.setCodigoTabela("Tab " + x);
            procedimento.setDataRealizacao(new Date());
            procedimento.setDescricaoServico("Descricao " + x);
            procedimento.setQuantidadeExecutada(x);
            procedimento.setValorGlosa(new BigDecimal(x * 1.50f).setScale(2));
            procedimento.setValorLiberado(new BigDecimal(x * 1.50f).setScale(2));
            procedimento.setValorProcessado(new BigDecimal(x * 1.50f).setScale(2));
            procedimentos.add(procedimento);
        }
        return procedimentos;
    }
}

Classes Models

Java guide.

package com.stackoverflow.pt.model;

import java.io.Serializable;
import java.math.BigDecimal;

public class Guia implements Serializable {

    private static final long serialVersionUID = 1581255960613739095L;

    private Beneficiario beneficiario;

    private BigDecimal valorProcessado;

    private BigDecimal valorLiberado;

    private BigDecimal valorGlosa;

    private Integer codigoGlosa;

    public Beneficiario getBeneficiario() {
        return beneficiario;
    }

    public void setBeneficiario(Beneficiario beneficiario) {
        this.beneficiario = beneficiario;
    }

    public BigDecimal getValorProcessado() {
        return valorProcessado;
    }

    public void setValorProcessado(BigDecimal valorProcessado) {
        this.valorProcessado = valorProcessado;
    }

    public BigDecimal getValorLiberado() {
        return valorLiberado;
    }

    public void setValorLiberado(BigDecimal valorLiberado) {
        this.valorLiberado = valorLiberado;
    }

    public BigDecimal getValorGlosa() {
        return valorGlosa;
    }

    public void setValorGlosa(BigDecimal valorGlosa) {
        this.valorGlosa = valorGlosa;
    }

    public Integer getCodigoGlosa() {
        return codigoGlosa;
    }

    public void setCodigoGlosa(Integer codigoGlosa) {
        this.codigoGlosa = codigoGlosa;
    }
}

Beneficiario.java

package com.stackoverflow.pt.model;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class Beneficiario implements Serializable {

    private static final long serialVersionUID = 1926001805008914921L;

    private String nome;

    private String identificador;

    private String guia;

    private String senha;

    private List<Procedimento> procedimentos;

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public String getIdentificador() {
        return identificador;
    }

    public void setIdentificador(String identificador) {
        this.identificador = identificador;
    }

    public String getGuia() {
        return guia;
    }

    public void setGuia(String guia) {
        this.guia = guia;
    }

    public String getSenha() {
        return senha;
    }

    public void setSenha(String senha) {
        this.senha = senha;
    }

    public List<Procedimento> getProcedimentos() {
        if (procedimentos == null) {
            procedimentos = new ArrayList<Procedimento>();
        }
        return procedimentos;
    }

    public void setProcedimentos(List<Procedimento> procedimentos) {
        this.procedimentos = procedimentos;
    }
}

Java procedure.

package com.stackoverflow.pt.model;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;

public class Procedimento implements Serializable {

    private static final long serialVersionUID = 4956642116624448639L;

    private Date dataRealizacao;

    private String descricaoServico;

    private String codigoTabela;

    private String codigoServico;

    private Integer quantidadeExecutada;

    private BigDecimal valorProcessado;

    private BigDecimal valorLiberado;

    private BigDecimal valorGlosa;

    private Integer codigoGlosa;

    public Date getDataRealizacao() {
        return dataRealizacao;
    }

    public void setDataRealizacao(Date dataRealizacao) {
        this.dataRealizacao = dataRealizacao;
    }

    public String getDescricaoServico() {
        return descricaoServico;
    }

    public void setDescricaoServico(String descricaoServico) {
        this.descricaoServico = descricaoServico;
    }

    public String getCodigoTabela() {
        return codigoTabela;
    }

    public void setCodigoTabela(String codigoTabela) {
        this.codigoTabela = codigoTabela;
    }

    public String getCodigoServico() {
        return codigoServico;
    }

    public void setCodigoServico(String codigoServico) {
        this.codigoServico = codigoServico;
    }

    public Integer getQuantidadeExecutada() {
        return quantidadeExecutada;
    }

    public void setQuantidadeExecutada(Integer quantidadeExecutada) {
        this.quantidadeExecutada = quantidadeExecutada;
    }

    public BigDecimal getValorProcessado() {
        return valorProcessado;
    }

    public void setValorProcessado(BigDecimal valorProcessado) {
        this.valorProcessado = valorProcessado;
    }

    public BigDecimal getValorLiberado() {
        return valorLiberado;
    }

    public void setValorLiberado(BigDecimal valorLiberado) {
        this.valorLiberado = valorLiberado;
    }

    public BigDecimal getValorGlosa() {
        return valorGlosa;
    }

    public void setValorGlosa(BigDecimal valorGlosa) {
        this.valorGlosa = valorGlosa;
    }

    public Integer getCodigoGlosa() {
        return codigoGlosa;
    }

    public void setCodigoGlosa(Integer codigoGlosa) {
        this.codigoGlosa = codigoGlosa;
    }
}

You can take advantage of this answer to learn too

Browser other questions tagged

You are not signed in. Login or sign up in order to post.