Club Delphi  
    FTP   CCD     Buscar   Trucos   Trabajo   Foros

Retroceder   Foros Club Delphi > Principal > OOP
Registrarse FAQ Miembros Calendario Guía de estilo Temas de Hoy

Grupo de Teaming del ClubDelphi

Respuesta
 
Herramientas Buscar en Tema Desplegado
  #1  
Antiguo 01-05-2007
amadis amadis is offline
Miembro
 
Registrado: may 2005
Ubicación: San José, Colón, Entre Ríos, Argentina
Posts: 315
Poder: 20
amadis Va por buen camino
Question STringGrid: cargar archivo previamente guardado.

Como les Va Gente!

Quisiera saber de que manera se puede leer un archivo creado con este procedimiento que encontré en el foro

Código Delphi [-]
procedure Guardar(Archivo: String; Grid: TStringGrid);
var
  i: integer;
begin
  with TStringList.Create do
  try
    for i:= 0 to Grid.RowCount - 1 do
      Add(Grid.Rows[i].CommaText);
    SaveToFile(Archivo);
  finally
    Free;
  end;
end;

Encontre esta forma de leer archivos, a la cual el cambie el SEPARADOR por COMA, pero no respeta las columnas ni filas.

Código Delphi [-]
procedure TForm1.Button1Click(Sender: TObject);
Const
Separador = ' '; //Este es el caracter que utilizamos de separador;
Var
Fichero : TStrings;
Sig : Integer;
Pos : Integer;
Copy_Ini : Integer;
Copy_Fin : Integer;
Longitud : Integer;
cTemp : String;
I, J, K : Integer;
////////////////////
Function pos_str(Cad : String; Car: Char; Ini : Integer) : Integer;
var
Cnt :Integer;
Longitud :Integer;
begin
Result := 0;
Longitud := Length(cad);
Cnt := Ini;
repeat
    Inc(Cnt);
    //Controlamos el separador y saltos de línea
    if (Cad[Cnt]=Car) or (Cad[Cnt]=#10) or (Cad[Cnt]=#13) then
    begin
        Result := Cnt -Ini;
        break;
    end;
until (Cnt > longitud) ;
end;
///////////////////////
begin
Fichero := TStringList.Create;
Fichero.LoadFromFile('Unit1.pas');  // Fichero a procesar
Longitud:=Length(Fichero.Text);
cTemp := Fichero.Text;
Fichero.Clear;
Pos:=0;

repeat
    Sig := Pos_Str(cTemp,Separador,Pos);
    if (sig=0) then break;
    Inc(pos,sig);
    copy_ini:=(pos-sig)+1;
    copy_fin:=sig-1;
    Fichero.Add(Trim(copy(cTemp,copy_ini,copy_fin)) );
until (sig=0);
//Acomodamos el StringGrid a la longitud del fichero, dependiendo del número de columnas.
StringGrid1.RowCount := (Fichero.Count -1) div StringGrid1.ColCount -1;
//Efectuamos el relleno del StringGrid

  K := 0;
  with StringGrid1 do
    for I := 0 to ColCount - 1 do
      for J:= 0 to RowCount - 1 do
        begin
          Cells[I,J] := Fichero[K]; 
          inc(K);
        end;

Fichero.Free;
end;
Responder Con Cita
  #2  
Antiguo 01-05-2007
luisgutierrezb luisgutierrezb is offline
Miembro
 
Registrado: oct 2005
Ubicación: México
Posts: 925
Poder: 19
luisgutierrezb Va por buen camino
Pues creo que puede ser algo asi como:

Código Delphi [-]
procedure Abrir(Archivo: String; Grid: TStringGrid);
var
  i: integer;
begin
  with TStringList.Create do
  try
    LoadFromFile(Archivo);
    Grid.RowCount := Count;
    for i:= 0 to Count - 1 do
      Grid.Rows[i].CommaText := Strings[i];
  finally
    Free;
  end;
end;

lo hice de memoria asi que puede fallar algo, pero la idea espero que si se comprenda
Responder Con Cita
  #3  
Antiguo 01-05-2007
amadis amadis is offline
Miembro
 
Registrado: may 2005
Ubicación: San José, Colón, Entre Ríos, Argentina
Posts: 315
Poder: 20
amadis Va por buen camino
tienes buena memoria

No pensé que fuera tan simple.
ANtes había intentado algo así pero teniendo en cuenta las columnas y me pardía.

Lo que escribiste funciona bien pero el problema es que no se cuantas FILAS tengo en el archivo.(y la STringGrid la inicio vacía)

Entonces agregé un TSTRINGLIST que cargo con el archivo CSV, cuento las filas que tiene y la guardo en una variable.
Para luego incrementar la STRINGGRID al numero de filas que tiene el archivo.

Aquí está el codigo que permite cargar un CSV a un grid sin saber cuantas lineas tenemos en el archivo

Código Delphi [-]
var
  i, filas: integer;
 Fichero : TStrings;
begin
abrirfile.Execute;
Fichero := TStringList.Create;
Fichero.LoadFromFile(abrirfile.FileName);  // Fichero a procesar
filas:= Fichero.Count;
Fichero.Free;
  with TStringList.Create do
  try
    LoadFromFile(abrirfile.FileName);
    STgrid.RowCount := filas;
    for i:= 0 to Count-1  do
      STgrid.Rows[i].CommaText := Strings[i];
  finally
    Free;
  end;

Última edición por amadis fecha: 01-05-2007 a las 18:23:10.
Responder Con Cita
  #4  
Antiguo 01-05-2007
Avatar de dec
dec dec is offline
Moderador
 
Registrado: dic 2004
Ubicación: Alcobendas, Madrid, España
Posts: 13.107
Poder: 34
dec Tiene un aura espectaculardec Tiene un aura espectacular
Hola,

¿Y esto no valdría igual? Pregunto.

Código Delphi [-]
var
  i: integer;
begin
  with TStringList.Create do
  try
    LoadFromFile(abrirfile.FileName);
    STgrid.RowCount := Count;
    for i:= 0 to Count-1  do
      STgrid.Rows[i].CommaText := Strings[i];
  finally
    Free;
  end;
__________________
David Esperalta
www.decsoftutils.com
Responder Con Cita
  #5  
Antiguo 01-05-2007
amadis amadis is offline
Miembro
 
Registrado: may 2005
Ubicación: San José, Colón, Entre Ríos, Argentina
Posts: 315
Poder: 20
amadis Va por buen camino
Lightbulb pues Si es lo mismo

No se que habría puesto antes que sólo me cargaba una fila del Grid.
Pensé que ese COUNT que inicialmente lo habia puesto tal como sugeria LuisGutierrezB era el count de rows de mi GRID (que estaba vacío)
Entonces creé un nuevo Stringlist para obtener el count.

Seguramente estaría mal generado el archivo con el que probaba o bien NO SE porque no me funcionó las veces que lo probé antes de cometer esa REDUNDANCIA.

Responder Con Cita
Respuesta



Normas de Publicación
no Puedes crear nuevos temas
no Puedes responder a temas
no Puedes adjuntar archivos
no Puedes editar tus mensajes

El código vB está habilitado
Las caritas están habilitado
Código [IMG] está habilitado
Código HTML está deshabilitado
Saltar a Foro

Temas Similares
Tema Autor Foro Respuestas Último mensaje
Cómo almacenar, editar y recuperar una archivo de imagen guardado en la base de datos JKM MS SQL Server 0 03-05-2006 22:29:41
Cargar Archivo srangel JAVA 0 03-09-2004 21:19:15
Exportar un StringGrid a un Archivo.TxT kokoyweb Varios 1 24-08-2004 22:04:26
ir a un registro guardado previamente pepe2000 Tablas planas 7 14-01-2004 11:35:19
Cargar archivo chm esocrates Varios 1 27-07-2003 09:58:02


La franja horaria es GMT +2. Ahora son las 02:03:32.


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
Copyright 1996-2007 Club Delphi