Club Delphi  
    FTP   CCD     Buscar   Trucos   Trabajo   Foros

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

Grupo de Teaming del ClubDelphi

Respuesta
 
Herramientas Buscar en Tema Desplegado
  #1  
Antiguo 02-04-2012
LuisAlf:: LuisAlf:: is offline
Miembro
 
Registrado: nov 2009
Posts: 60
Poder: 15
LuisAlf:: Va por buen camino
Stringgrid a Excel

Hola a todos!

Estoy de regreso por aquí por un problema con este truco que encontre en el club DELPHI (Exportar un stringGrid a Excel)

http://www.clubdelphi.com/trucos/ind...l=0&scrollb=88

Primero: Tuve que crear la unit "Excel_TLB", porque la ponia en la sección de "uses" y no la reconocia: menú Project> Import Type Library...

Segundo: Al compilar de nuevo mi proyecto me saltarón errores en estas partes del procedimiento del truco:

Código Delphi [-]
             
try
  if pos('/', cells[i, linea - 1]) <> 0 then begin
    AuxFecha := strtodatetime(cells[i, linea - 1]));//<<<<<<<<<<<<<----------------------
    ws.Cells.Item[ExLin, ExCol] := AuxFecha;
  end
  else AuxFecha := strtodatetime('GENERA EXCEPCION'); 
except

Según mi deducción fue porque habia un parentesis demás y lo borre.

Después pude correr mi aplicación pero al accionar el botón de exportación salta un error en el try... Diciendo que:

raised exception class EConvertError with message "GENERA EXCEPCION' is not a valid date and time'.

Y allí ya no se que hacer para que me funcione la exportación a excel

Si alguien me pudiera orientar para hacer funcionar el código se lo agradeceria grandemente...
Responder Con Cita
  #2  
Antiguo 02-04-2012
Avatar de ecfisa
ecfisa ecfisa is offline
Moderador
 
Registrado: dic 2005
Ubicación: Tres Arroyos, Argentina
Posts: 10.508
Poder: 36
ecfisa is a splendid one to beholdecfisa is a splendid one to beholdecfisa is a splendid one to beholdecfisa is a splendid one to beholdecfisa is a splendid one to beholdecfisa is a splendid one to beholdecfisa is a splendid one to behold
Hola LuisAlf.

Mirando el enlace pareciera que se trata de determinar el tipo de dato almacenado en cada celda (comprendida en un rango) del TStringGrid para pasarlo al tipo correspondiente a la planilla de Excel.

No utilizo Excel por lo que no tengo forma de probarlo, pero yo haría las comprobaciones de este modo:
Código Delphi [-]
var
  DTimeAux: TDateTime;
  IntAux: Integer;
  FloatAux: Extended;
  ...
begin
  ... 
  if TryStrToDateTime(StringGrid1.Cells[i, linea-1], DTimeAux) then 
    ws.Cells.Item[ExLin, ExCol]:= DTimeAux
  else if TryStrToInt(StringGrid1.Cells[i, linea-1], IntAux) then
    ws.Cells.Item[ExLin, ExCol] := IntAux
  else if TryStrToFloat(StringGrid1.Cells[i, linea-1],FloatAux) then
    ws.Cells.Item[ExLin, ExCol]:= FloatAux
  else
    ws.Cells.Item[ExLin, ExCol]:= Cells[i,ARow];
  ...
Me parece un modo más natural que el tratamiento mediante try/except.



Una forma mas reducida (no sé si funcione, tendrías que probar) , sería:
Código Delphi [-]
  ...
  if not TryStrToDateTime(StringGrid1.Cells[i, linea-1], ws.Cells.Item[ExLin, ExCol]) then
  else if not TryStrToInt(StringGrid1.Cells[i, linea-1], ws.Cells.Item[ExLin, ExCol]) then
  else if not TryStrToFloat(StringGrid1.Cells[i, linea-1], ws.Cells.Item[ExLin, ExCol]) then
  else
    ws.Cells.Item[ExLin, ExCol]:= Cells[i,ARow];
  ...

Saludos.
__________________
Daniel Didriksen

Guía de estilo - Uso de las etiquetas - La otra guía de estilo ....
Responder Con Cita
  #3  
Antiguo 03-04-2012
LuisAlf:: LuisAlf:: is offline
Miembro
 
Registrado: nov 2009
Posts: 60
Poder: 15
LuisAlf:: Va por buen camino
Hola Ecfisa!

Antes que nada gracias por tu ayuda.

Sabes que estuve probando tu recomendación y me parece mucho mejor que todos esos try anidados...

El problema es que no pude solucionar nada! haaha

Código Delphi [-]
procedure Tform2.ExportaExcel(pStringGrid : TstringGrid; c0,r0,c1,r1 : Integer);
var ExLin, ExCol, i, Linea, AuxInteger : Integer;
    AuxFloat : Extended;
    AuxFecha : tDatetime;
    c : TCursor;
    Excel, ExcelDoc, WS : Variant;
begin
  c             := Screen.Cursor;
  Screen.Cursor := crHourGlass;
  with pStringGrid do begin
    try
      coinitialize(nil);
      Excel         := CreateOleObject('Excel.Application');
      ExcelDoc      := Excel.Workbooks.Add;
      WS            := ExcelDoc.ActiveSheet;
      Excel.Visible := true;
      ExCol         := 0;
      for i := c0 to c1 do begin
        inc(ExCol);
        ws.Cells.Item[1, ExCol]:= cells[i, 0];
      end;

      for linea := r0 to r1 do begin
        inc(ExLin);
        ExCol := 0;
        for i := c0 to c1 do begin
          inc(ExCol);

          if TryStrToInt(StringGrid1.Cells[i, linea-1], AuxInteger) then
            ws.Cells.Item[ExLin, ExCol] := AuxInteger
          else if TryStrToFloat(StringGrid1.Cells[i, linea-1],AuxFloat) then
            ws.Cells.Item[ExLin, ExCol]:= AuxFloat
          else
            ws.Cells.Item[ExLin, ExCol]:= StringGrid1.Cells[i,linea-1];
           //showmessage(ws.Cells.Item[ExLin, ExCol]);
        end;
      end;
       ws.cells.entirecolumn.autofit;
    finally
      screen.Cursor := c;
    end;

  end;//del with
end;

Ya no salta error pero no me exporta correctamente... decidí darme a la busqueda de otras soluciones y encontre una, por medio de la ayuda de OLE... Como lo explica muy claramente roman en este hilo:

http://www.clubdelphi.com/foros/showthread.php?t=22649

Bueno muchas gracias de cualquier forma!
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
Abrir un archivo excel en un stringgrid con Lazarus IDE jejo1984 Lazarus, FreePascal, Kylix, etc. 9 16-01-2012 14:46:49
Importar datos de Excel a un StringGrid. ingabraham Varios 4 19-06-2011 00:49:00
StringGrid con columnas igual al de un archivo Excel J@ckie Conexión con bases de datos 3 01-03-2011 15:07:20
Exportar Stringgrid a Excel santipeich C++ Builder 9 15-06-2008 06:12:47


La franja horaria es GMT +2. Ahora son las 17:21:35.


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