Foros Club Delphi

Foros Club Delphi (https://www.clubdelphi.com/foros/index.php)
-   Varios (https://www.clubdelphi.com/foros/forumdisplay.php?f=11)
-   -   Stringgrid a Excel (https://www.clubdelphi.com/foros/showthread.php?t=78251)

LuisAlf:: 02-04-2012 05:46:22

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...

ecfisa 02-04-2012 08:52:22

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.

LuisAlf:: 03-04-2012 01:32:58

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 :p

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! :D ;)


La franja horaria es GMT +2. Ahora son las 23:36:43.

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