Foros Club Delphi

Foros Club Delphi (https://www.clubdelphi.com/foros/index.php)
-   Varios (https://www.clubdelphi.com/foros/forumdisplay.php?f=11)
-   -   Como hacer para totalizar una columna de un stringgrid por valor (https://www.clubdelphi.com/foros/showthread.php?t=82177)

steelha 08-02-2013 14:07:14

Muchas gracias duilioisola por la ayuda, el código es perfecto ya he hecho unos arreglos extras y todo marcha de maravillas. Dure mucho para darme cuenta que no era que no estaba acumulando valor sino que me repetia el nombre anterior para eso guardo en variables extras ... Publico codigo para aquellos que lo necesiten.

Código Delphi [-]
unit leeruniversal;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, Buttons;

type
  TForm1 = class(TForm)
    ButtonAgrupar: TBitBtn;
    OpenDialog1: TOpenDialog;
    Label1: TLabel;
    Label2: TLabel;
    BitBtn1: TBitBtn;
    procedure ButtonAgruparClick(Sender: TObject);
    procedure BitBtn1Click(Sender: TObject);
  private
    { Private declarations }
    detener : string;
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.ButtonAgruparClick(Sender: TObject);
var
   s1, s2 : TStringList;
   archivo: string;
   monto, nombre, autoriz, fecha : string;
   anombre, aautoriz, afecha : string;
   i : Integer;
   cant : Integer;
   conv : Double;
   ruta : string;
   dia  : Word;
   mes  : Word;
   ano  : Word;
   hor  : Word;
   min  : Word;
   sec  : Word;
   mil  : Word;
   romp : string;
   total: Real;
   erro : Integer;
   errl : string;
   linea: string;
   taman: Integer;
   orig : string;
begin
   // inicializo variables
   detener := 'N';
   autoriz :='';
   nombre := '';
   fecha :='';
   aautoriz :='';
   anombre := '';
   afecha :='';
   errl   := '';
   linea:='';
   total := 0;
   cant := 0;
   erro := 0;
   orig := '0402364972811201203003798  118     12424409       A010010010100013402000000000014450PEÑA  PAULA                                                                                         903856  ';
   taman:= Length(orig);

   // Creo StringLists para trabajar con los textos
   s1 := TStringList.Create;
   s2 := TStringList.Create;
   try
      // Pido datos origen
      OpenDialog1.Execute;
      archivo := OpenDialog1.FileName;

      // Cargar archivo de texto
      s1.LoadFromFile(archivo);

      // Obtengo el nombre del fichero destino
      DecodeDate(Now,ano,mes,Dia);
      DecodeTime(Now,hor,min,sec,mil);
      ruta := OpenDialog1.InitialDir +'Universal_'+inttostr(Dia)+inttostr(mes)+inttostr(ano)+'_'+inttostr(hor)+inttostr(min)+inttostr(sec  )+'.txt';

      // Inicializo romp con el valor de la primera linea
      romp := Trim(Copy(s1[0], 36, 8)); // ROMPER POR AUTORIZACION
      anombre := Trim(Copy(s1[i], 85, 60));  // PRIMER NOMBRE
      aautoriz := Trim(Copy(s1[i], 36, 8)); // PRIMERA AUTORIZACION
      afecha := Trim(Copy(s1[i], 10, 8));   // PRIMERA FECHA AUTORIZACION

      // Recorro todo el archivo
      for i := 0 to (s1.Count-1) do
      begin
         if Length(s1.Strings[i]) = taman then
         begin
           monto := Trim(Copy(s1[i], 70, 15));   // MONTO
           nombre := Trim(Copy(s1[i], 85, 60));  // NOMBRE
           autoriz := Trim(Copy(s1[i], 36, 8)); // AUTORIZACION
           fecha := Trim(Copy(s1[i], 10, 8));   // FECHA AUTORIZACION

           // Datos completos no error de separacion de lineas
           If (monto <> '') and (nombre <> '') and (autoriz <> '') then
             begin
                // Colocar punto al monto
                try
                   conv := (StrToFloat(monto)*0.01);
                   monto := FloatToStr(conv);
                except
                   monto := '0.00';
                   erro := erro + 1;
                   Label1.Caption := 'Cantidad de errores encontrados = ' +  IntToStr(erro);
                end;
             end;

            // Si la autorizacion no es vacia
           If Trim(autoriz) <> '' then
            begin
               // Si cambio el campo autorizacion, creo un registro e inicializo total
               If Trim(autoriz) <> Trim(romp) then
               begin
                  linea := '';
                  linea := afecha + #9 + anombre + #9 + '0000000' + #9 + '0000000' + #9 + '0000000' + #9 + aautoriz + #9 + FloatToStr(total) + #9 + FloatToStr(total);
                  s2.Add(linea);
                  total := 0;
                  romp  := Trim(autoriz);
                  anombre := nombre;
                  afecha  := fecha;
                  aautoriz:= autoriz;
               end;
            end;

            // Acumulo monto
            total := total + StrToFloat(monto);

            // Cuento lineas tratadas
            cant := cant + 1;
            Label2.Caption := IntToStr(cant);
            Application.ProcessMessages;

            If Detener = 'S' then
              Break;
          end
         else
            begin
              errl := errl + 'Error en Linea '+IntToStr(i)+' - '+ s1.Strings[i]+ ' (TAMAÑO DE LINEA NO COINCIDEN) '+#13;
            end;
         end;

      // Terminé de recorrer pero todavía tengo un ultimo total
      If (total > 0) then
      begin
         linea := '';
         linea := afecha + #9 + anombre + #9 + '0000000' + #9 + '0000000' + #9 + '0000000' + #9 + aautoriz + #9 + FloatToStr(total) + #9 + FloatToStr(total);
         s2.Add(linea);
      end;


      // Guardo las lineas agrupadas
      s2.SaveToFile(ruta);
      ShowMessage(errl);
   finally
      // Libero StringGrids
      s1.Free;
      s2.Free;
   end;

   // Termino aplicacion
   Application.Terminate;
end;

procedure TForm1.BitBtn1Click(Sender: TObject);
begin
  detener := 'S';
end;

end.

duilioisola 08-02-2013 14:18:22

Ten en cuenta que donde inicializas algunas variables estás utilizando i, que no está inicializada y puede contener basura.

Código Delphi [-]
      // Inicializo romp con el valor de la primera linea
      romp := Trim(Copy(s1[0], 36, 8)); // ROMPER POR AUTORIZACION
      anombre := Trim(Copy(s1[i], 85, 60));  // PRIMER NOMBRE
      aautoriz := Trim(Copy(s1[i], 36, 8)); // PRIMERA AUTORIZACION
      afecha := Trim(Copy(s1[i], 10, 8));   // PRIMERA FECHA AUTORIZACION

Creo que deberías reemplazar la variable i por un 0 en todas estas líneas.

steelha 08-02-2013 15:37:20

Gracias no me habia percatado de ese error, por eso del refran DOS OJOS EN BUEN ESTADOS VEN MAS QUE LOS MIOS CON LENTES :p


La franja horaria es GMT +2. Ahora son las 17:44:49.

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2024, Jelsoft Enterprises Ltd.
Traducción al castellano por el equipo de moderadores del Club Delphi