Foros Club Delphi

Foros Club Delphi (https://www.clubdelphi.com/foros/index.php)
-   Varios (https://www.clubdelphi.com/foros/forumdisplay.php?f=11)
-   -   problemas al guardar listview (https://www.clubdelphi.com/foros/showthread.php?t=76776)

demonio6 26-11-2011 19:38:42

problemas al guardar listview
 
Problemas al guardar listview

Un amigo esta creando un scaner y al parecer no puede guardar la información de este listview, la idea era guardarlo como txt y/o csv; el codigo era similar a este:

Código Delphi [-]
S := TStringList.Create; 
for i := 0 to ListView1.Items.Count-1 do 
  S.Add(ListView1.Items[i].Caption +','+ ListView1.Items[i].SubItems.CommaText);  
  S.SaveToFile('archivo.txt'); 
  S.Free;

Neftali [Germán.Estévez] 28-11-2011 13:03:48

¿Y qué le pasa cuando ejecuta ese código?
¿ Algún error?

La primera recomendación es que utilices el nombre de archivo con el path completo.

Pruébalo o dile a tu amigo que lo prueba y a ver qué pasa.

demonio6 30-11-2011 21:40:51

un error era porq no había definido la S y la i, pero al definirlas se ejecuto normal pero al momento de guardar este se cuelga, y tira para enviar información a microsoft y no guarda nada, siquiera crea el archivo.

Casimiro Notevi 30-11-2011 21:52:36

Bienvenido a clubdelphi, ¿ya leiste nuestra guía de estilo?, gracias por tu colaboración.

olbeup 30-11-2011 21:54:04

Cita:

Empezado por demonio6 (Mensaje 419561)
Problemas al guardar listview

Un amigo esta creando un scaner y al parecer no puede guardar la información de este listview, la idea era guardarlo como txt y/o csv; el codigo era similar a este:

Código Delphi [-]
S := TStringList.Create; 
for i := 0 to ListView1.Items.Count-1 do 
  S.Add(ListView1.Items[i].Caption +','+ ListView1.Items[i].SubItems.CommaText);  
  S.SaveToFile('archivo.txt'); 
  S.Free;

No hay ningún error en el código, lo he realizado yo mismo y funciona correctamente guardando el archivo, como dice Neftali, puede ser que te falte el path.

Un saludo.

BioStudio 05-11-2012 17:04:45

mm
 
mm lo raro q a mi no me funciona, defini todo pero nada, se crea el archivo pero no guarda nada... ;(

nlsgarcia 05-11-2012 18:39:12

BioStudio,

Revisa este código:
Código Delphi [-]
procedure TForm1.Button1Click(Sender: TObject);
var
   S : TStringList;
   i : Integer;
   Item : String;

begin

   S := TStringList.Create;

   for i := 0 to ListView1.Items.Count-1 do
   begin
      Item := ListView1.Items.Item[i].Caption + ',' + ListView1.Items[i].SubItems.CommaText;
      S.Add(Item);
   end;

   S.SaveToFile(ExtractFilePath(Application.ExeName) + 'archivo.csv');
   S.Free;

end;
Este código genera un archivo CSV con los elementos del Listview en el directorio de la aplicación.

Espero sea útil :)

Nelson.

nlsgarcia 05-11-2012 20:41:52

BioStudio,

Revisa este link : http://www.delphigeist.com/2009/10/t...w-and-csv.html

En el encontraras un ejemplo descargable del uso de TListView y archivos CSV.

El ejemplo del link lo modifique ligeramente para que pueda funcionar en Delphi 7 y esta disponible en : http://terawiki.clubdelphi.com/Delph...ew_CSV_src.rar

Espero sea útil :)

Nelson.

BioStudio 06-11-2012 02:20:36

y por ejemplo si el ListView1 lo tienes en el Form1, como puedes desde el Form2 guardar su contenido?

ecfisa 06-11-2012 03:34:30

Cita:

Empezado por BioStudio (Mensaje 448705)
y por ejemplo si el ListView1 lo tienes en el Form1, como puedes desde el Form2 guardar su contenido?

Hola.


Form2:
Código Delphi [-]
...
implementation

uses Unit1; (* Form1 *)

procedure TForm2.btnGuardarListViewClick(Sender: TObject);
var
  i : Integer;
begin
  with TStringList.Create do
  try
    for i := 0 to Form1.ListView1.Items.Count-1 do
      Add(Form1.ListView1.Items[i].Caption +','+
          Form1.ListView1.Items[i].SubItems.CommaText);
    SaveToFile('archivo.txt')
  finally
    Free
  end
end;
...

Saludos.

BioStudio 06-11-2012 03:45:34

Gracias por toda la ayuda!

Use similar pero para agregar datos:

Código Delphi [-]
var
  Form3: TForm3;

implementation

uses umain;
{$R *.dfm}

procedure TForm3.Button1Click(Sender: TObject);
begin
// Agregar información a la Tabla.

with umain.Form1.ListView1.Items.Add do
    begin
      Caption := '2';            // Columna 0
      SubItems.Add( '1' );           // Columna 2
      SubItems.Add( 'MONITOR LG' );  // Columna 3
      SubItems.Add( '3' );           // Columna 4
      SubItems.Add( '230,45' );      // Columna 5
    end;
end;

end.

BioStudio 08-11-2012 02:10:53

Si bien el codigo de ecfisa esta perfecto, el CSV se hace con ";" por ende simplemente modificamos:

Código Delphi [-]
Add(Form1.ListView1.Items[i].Caption +';'+ 
Form1.ListView1.Items[i].SubItems[0] +';'+ 
Form1.ListView1.Items[i].SubItems[1] +';'+ 
Form1.ListView1.Items[i].SubItems[2] +';'+ 
Form1.ListView1.Items[i].SubItems[3]);

Para 4 columnas.

BioStudio 08-11-2012 02:41:56

Ahora por ejemplo le quise agregar el saveDialog pero no crea el archivo:

Código Delphi [-]
var
  i : Integer;
  saveDialog : TSaveDialog;    // Save dialog variable
begin
  saveDialog := TSaveDialog.Create(self);
  saveDialog.Title := 'Guarde su información';
  saveDialog.InitialDir := GetCurrentDir;
  saveDialog.Filter := 'CSV (Formato de texto separado por comas)|*.csv|';
  saveDialog.DefaultExt := 'csv';
  saveDialog.FilterIndex := 1;

  if saveDialog.Execute then //ShowMessage('Archivo : '+saveDialog1.FileName)
     saveDialog := TSaveDialog.Create(self);
      with TStringList.Create do
        try
          for i := 0 to umain.Form1.ListView1.Items.Count-1 do
            Add(Form1.ListView1.Items[i].Caption +';'+ 
            Form1.ListView1.Items[i].SubItems[0] +';'+ 
            Form1.ListView1.Items[i].SubItems[1] +';'+ 
            Form1.ListView1.Items[i].SubItems[2] +';'+ 
            Form1.ListView1.Items[i].SubItems[3]);
            ExtractFilePath(Application.ExeName);
          finally
          Free
      end
  else ShowMessage('Se ha cancelado el guardado del archivo.');
  saveDialog.Free;

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

end;

ecfisa 08-11-2012 04:01:12

Hola BioStudio.

Creo que te va a resultar mas simple de este modo:
Código Delphi [-]
....
var
  i : Integer;
begin
  ...
  with TStringList.Create do
  try
    for i := 0 to Form1.ListView1.Items.Count-1 do
      Add(Form1.ListView1.Items[i].Caption +','+
          Form1.ListView1.Items[i].SubItems.CommaText);
      Text := StringReplace(Text,',',';',[rfReplaceAll]);
    SaveToFile('archivo.txt')
  finally
    Free
  end
end;

Saludos.

nlsgarcia 08-11-2012 05:42:13

BioStudio,

Cita:

Empezado por BioStudio (Mensaje 448897)
Ahora por ejemplo le quise agregar el saveDialog pero no crea el archivo

Esta sentencia esta respetida 2 veces en tu código:
Código Delphi [-]
   saveDialog := TSaveDialog.Create(self);
Esta es una combinación de tu código con el de ecfisa:
Código Delphi [-]
procedure TForm1.Button1Click(Sender: TObject);
var
  i : Integer;
  saveDialog : TSaveDialog;

begin

  saveDialog := TSaveDialog.Create(self);
  saveDialog.Title := 'Respaldo de Archivo en Formato CSV';
  saveDialog.InitialDir := GetCurrentDir;
  saveDialog.Filter := 'CSV (Formato de texto separado por comas)|*.csv';
  saveDialog.DefaultExt := 'csv';
  saveDialog.FilterIndex := 1;

  if saveDialog.Execute then
  begin
     with TStringList.Create do
     try
        for i := 0 to Form1.ListView1.Items.Count-1 do
           Add(Form1.ListView1.Items[i].Caption +',' +
               Form1.ListView1.Items[i].SubItems.CommaText);
           Text := StringReplace(Text,',',';',[rfReplaceAll]);
           try
              SaveToFile(SaveDialog.FileName);
           except
              ShowMessage('Error en la Generación del Archivo CSV');
           end;
     finally
        free;
     end;
  end;

  saveDialog.Free;

end;
Espero sea útil :)

Nelson.

BioStudio 09-11-2012 01:34:34

Gracias nuevamente por tu ayuda nlsgarcia!

Para completar un poquito más dejo uno para TXT:

Código Delphi [-]
procedure TForm2.BitBtn1Click(Sender: TObject);

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

var
  i : Integer;
  saveDialog : TSaveDialog;

begin

  saveDialog := TSaveDialog.Create(self);
  saveDialog.Title := 'Respaldo de Archivo en Formato TXT';
  saveDialog.InitialDir := GetCurrentDir;
  saveDialog.Filter := 'Texto (delimitado por tabulaciones) (*.txt)|*.txt';
  saveDialog.DefaultExt := 'txt';
  saveDialog.FilterIndex := 1;

  if saveDialog.Execute then
  begin
     with TStringList.Create do
     try
        for i := 0 to umain.Form1.ListView1.Items.Count-1 do
           Add(umain.Form1.ListView1.Items[i].Caption +',' +
               umain.Form1.ListView1.Items[i].SubItems.CommaText);
           Text := StringReplace(Text,',',#9,[rfReplaceAll]);
           try
              SaveToFile(SaveDialog.FileName);
           except
              ShowMessage('Error en la Generación del Archivo TXT');
           end;
     finally
        free;
     end;
  end;

  saveDialog.Free;

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
end;

y uno para PRN:

Código Delphi [-]
procedure TForm2.Button1Click(Sender: TObject);
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

var
  i : Integer;
  saveDialog : TSaveDialog;

begin

  saveDialog := TSaveDialog.Create(self);
  saveDialog.Title := 'Respaldo de Archivo en Formato PRN';
  saveDialog.InitialDir := GetCurrentDir;
  saveDialog.Filter := 'Texto con formato (delimitado por espacios) (*.prn)|*.prn';
  saveDialog.DefaultExt := 'prn';
  saveDialog.FilterIndex := 1;

  if saveDialog.Execute then
  begin
     with TStringList.Create do
     try
        for i := 0 to umain.Form1.ListView1.Items.Count-1 do
           Add(umain.Form1.ListView1.Items[i].Caption +',' +
               umain.Form1.ListView1.Items[i].SubItems.CommaText);
           Text := StringReplace(Text,',',#32,[rfReplaceAll]);
           try
              SaveToFile(SaveDialog.FileName);
           except
              ShowMessage('Error en la Generación del Archivo PRN');
           end;
     finally
        free;
     end;
  end;

  saveDialog.Free;

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

end;

BioStudio 11-11-2012 05:35:52

Nueva cuestión, Exportar ListView a imagen BMP!
 
Sigo el post para no crear múltiples y que se pueda encontrar todo en uno. Resulta que nuevamente usando un ListView, encontré un CODE en la red para imprimirlo, en teoría no es imprimirlo con impresora sino que es tomarlo y guardarlo en un archivo de imagen *.BMP:

Código Delphi [-]
procedure TForm2.Button2Click(Sender: TObject);
var
  bmp: TBitmap;
begin
  bmp := TBitmap.Create;
  try
    bmp.Width := ListView1.Width;
    bmp.Height := ListView1.Height;
    bmp.Canvas.Lock;
    try
      ListView1.Perform(WM_PRINT, bmp.Canvas.Handle, PRF_CHILDREN or PRF_CLIENT or PRF_NONCLIENT);
    finally
      bmp.Canvas.UnLock;
      bmp.SaveToFile('C:\tree.bmp')
    end;
  finally
    bmp.Free
  end;
end;

Pero el problema esta en que al quererlo guardar por ejemplo si tenemos 1000 datos en un listview, seguramente se nos creara un Scroll (abajo/arriba), pero lo unico que hace es capturar tal cual es el tamaño del ListView y no imprime los 1000 datos que debe. Hay alguna manera de realizar esto??? :confused:

Luego, también encontré un CODE muy bueno pero que le falta algo, es para exportar directamente un ListView a Microsoft Excel XXXX (en mi caso 2010), pero me lanza el siguiente errror:

i.minus.com/ibrVRjaEZAgSsn.png

El code es:

Código Delphi [-]
!**************************************
! Name: Listview contents to Excel
! Description:Exports data in a TListview to an Excel spreadsheet
! By: Brett Perry
!
! Returns:A formatted Excel spreadsheet
!
! Assumes:Converts data from TListview to Excel Spreadsheet
!
! Side Effects:Must have Excel installed on client machine but errors are trapped
!
!This code is copyrighted and has! limited warranties.Please see Planet-Source-Code .com/vb/scripts/ShowCode.asp?txtCodeId=768&lngWId=7!fordetails.!**************************************

procedure ListDataToExcel;
var
 {excel}
 Sheet,objExcel : Variant;
 Title : String;
 x,y: Integer;
 tmpDate : TDateTime; 
begin
 Screen.Cursor := crHourGlass;
 try
Title := 'Listview Data To Excel';
{create an instance of excel}
objExcel := CreateOleObject ('Excel.Application');
objExcel.Visible := True;
objExcel.Caption := 'Your CAPTION in Excel here';
{add the sheet}
objExcel.Workbooks.Add;
objExcel.Workbooks[1].Sheets.Add;
objExcel.Workbooks[1].WorkSheets[1].Name := Title;
Sheet := objExcel.Workbooks[1].WorkSheets[Title];
{create the columns}
for x := 0 to (lvList.Columns.Count -1) do
 Sheet.Cells[1, (x + 1)] := lvList.Columns.Items[x].Caption;
for y := 0 to (lvList.Items.Count -1) do
begin
      Sheet.Cells[(y + 3),1] := lvList.Items.Item[y].Caption;
  for x := 0 to (lvList.Columns.Count - 2) do
 begin
   try
  {check if output is date and add to excel in correct format}
  tmpDate := StrToDate(lvList.Items.Item[y].SubItems.Strings[x]);
 Sheet.Cells[(y + 3), (x + 2)] := tmpDate;
 objExcel.Selection.NumberFormat := 'dd/mm/yyyy';
 except on EConvertError do
 begin
   {if there was a conversion error then just add as normal i.e. string}
   Sheet.Cells[(y + 3), (x + 2)] := lvList.Items.Item[y].SubItems.Strings[x];
    end;
   end;
 end;
end;
{Select cells and format}
objExcel.Cells.select;
objExcel.Selection.Font.Name:='Arial';
objExcel.Selection.Font.Size:=9;
objExcel.selection.Columns.AutoFit;
except
begin
 Screen.Cursor := crDefault;
 MessageDlg('Excel transaction cancelled.',mtInformation, [mbOK],0);
 exit;
end;
 end;
 Screen.Cursor := crDefault; 
end;


La franja horaria es GMT +2. Ahora son las 05:40:58.

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