Ir al contenido


Foto

Exportar un DataSet a Excel


  • Por favor identifícate para responder
13 respuestas en este tema

#1 enecumene

enecumene

    Webmaster

  • Administrador
  • 7.419 mensajes
  • LocationRepública Dominicana

Escrito 06 enero 2017 - 10:02

Aquí dejo cómo podemos exportar el resultado de un DataSet a un Archivo Excel, para quien le pueda ser útil, en mi caso utilicé el TFDQuery, pero es aplicable para cualquier otro, el código incluye una barra de progreso:


delphi
  1. procedure TFInvGeneral.exportToExcel(AData: TFDQuery; AProgreso: TProgressBar);
  2. procedure ProgressBarInit;
  3. begin
  4. AProgreso.Max := AData.RecordCount;
  5. AProgreso.Position := 0;
  6. AProgreso.Visible := True;
  7. end;
  8.  
  9. var ExcelApp, Libro: Variant;
  10. fila, i:integer;
  11. Columnas: TStringList;
  12. begin
  13.  
  14. Columnas := TStringList.Create;
  15. Columnas.Add('Código');
  16. Columnas.Add('Referencia');
  17. Columnas.Add('Insumo/Pieza');
  18. Columnas.Add('Marca');
  19. Columnas.Add('Existencia');
  20. Columnas.Add('Condición');
  21. Columnas.Add('Area');
  22. Columnas.Add('Costo');
  23.  
  24. //svGuardar es un SaveDialog para poder especificar la ruta del archivo
  25. svGuardar.Title := 'Exportando Reporte a Excel';
  26. svGuardar.DefaultExt := '*.xlsx';
  27.  
  28. svGuardar.Filter := 'Archivos Excel (*.xls,*.xlsx)|*.xls;*.xlsx';
  29. svGuardar.FilterIndex := 1;
  30.  
  31. try
  32. svGuardar.Execute;
  33. if (svGuardar.FileName <> '') then
  34. begin
  35. // Comprobar si existe el component TProgressBar
  36. if (AProgreso <> nil) then
  37. ProgressBarInit;
  38.  
  39. //Deshabilitamos los controles
  40. AData.DisableControls;
  41.  
  42. //Creamos el archivo Excel
  43. ExcelApp := CreateOleObject('Excel.Application');
  44.  
  45. //Evitamos mostrar las alertas propias de Excel
  46. ExcelApp.DisplayAlerts := false;
  47.  
  48. // Añadimos una Hoja
  49. ExcelApp.WorkBooks.Add();
  50.  
  51. // Colocamos el Nombre de la Hoja
  52. ExcelApp.WorkBooks[1].ActiveSheet.Name := 'Inventario';
  53.  
  54. // Activamos la hoja la cual trabajaremos
  55. Libro := ExcelApp.WorkBooks[1].ActiveSheet;
  56.  
  57. // Orientación de página
  58. //1 - Vertical y 2 - Horizontal
  59. Libro.PageSetup.Orientation := 1;
  60.  
  61. //Agregamos la primera fila con la cabecera
  62. for i:= 0 to Columnas.count - 1 do
  63. begin
  64. Libro.Cells[1,i+1] := Columnas.Strings[i];
  65. Libro.Cells[1,i+1].Font.Bold := True;
  66. Libro.Cells[1,i+1].font.Size := 12;
  67. Libro.Cells[1,i+1].font.Color := clWhite;
  68. Libro.Cells[1,i+1].Interior.Color := clGray ;
  69. Libro.Cells[1,i+1].HorizontalAlignment := -4108; //-4108 corresponde al centralizado del texto
  70. end;
  71.  
  72. // Ahora cargaremos los datos
  73.  
  74. //Empezamos desde la segunda fila
  75. //Recordar que la primera es la cabecera
  76. fila := 2;
  77.  
  78. //Lo dejamos en Segundo Plano
  79. ExcelApp.Visible := False;
  80.  
  81. AData.First;
  82. while not AData.eof do begin
  83. //Código
  84. Libro.Cells[fila,1].NumberFormat := '0';
  85. Libro.Cells[fila,1] := AData.FieldByName('INS_ID').AsInteger;
  86.  
  87. //Referencia
  88. Libro.Cells[fila,2].NumberFormat := RPad('0', '0', Length(AData.FieldByName('INS_REF').AsString));
  89. Libro.Cells[fila,2] := AData.FieldByName('INS_REF').AsString;
  90.  
  91. //Insumo/Pieza
  92. Libro.Cells[fila,3].NumberFormat := RPad('0', '0', Length(AData.FieldByName('INS_NOMBRE').AsString));
  93. Libro.Cells[fila,3] := AData.FieldByName('INS_NOMBRE').AsString;
  94.  
  95. //Marca
  96. Libro.Cells[fila,4].NumberFormat := RPad('0', '0', Length(AData.FieldByName('INS_MARCA').AsString));
  97. Libro.Cells[fila,4] := AData.FieldByName('INS_MARCA').AsString;
  98.  
  99. //Existencia
  100. Libro.Cells[fila,5].NumberFormat := '0.00';
  101. Libro.Cells[fila,5] := AData.FieldByName('INS_EXISTENCIA').asFloat;
  102.  
  103. //Condicion
  104. Libro.Cells[fila,6].NumberFormat := RPad('0', '0', Length(getCondicion(AData.FieldByName('INS_CONDICION').AsInteger)));
  105. Libro.Cells[fila,6] := getCondicion(AData.FieldByName('INS_CONDICION').AsInteger);
  106.  
  107. //Area
  108. Libro.Cells[fila,7].NumberFormat := RPad('0', '0', Length(getArea(AData.FieldByName('INS_AREA').AsInteger)));
  109. Libro.Cells[fila,7] := getArea(AData.FieldByName('INS_AREA').AsInteger);
  110.  
  111. //Costo
  112. Libro.Cells[fila,8].NumberFormat := '0.00';
  113. Libro.Cells[fila,8] := AData.FieldByName('INS_COSTE').AsFloat;
  114.  
  115. //Autofijamos las columnas
  116. Libro.Cells.Columns.Autofit;
  117.  
  118. //Siguiente Fila
  119. Inc(Fila);
  120.  
  121. AProgreso.Position := AProgreso.Position + 1;
  122.  
  123. AData.Next;
  124. end;
  125.  
  126. AData.EnableControls;
  127.  
  128. Libro.SaveAs(svGuardar.FileName);
  129.  
  130. if AProgreso.Position = AData.RecordCount then begin
  131. MessageDLG('¡Se exportó correctamente!',mtInformation,[mbOk],0);
  132. ExcelApp.Visible := True;
  133. end;
  134. end; //if svGuardar.FileName <> ''
  135. except
  136. ExcelApp.Quit;
  137. AData.EnableControls;
  138. Showmessage('No se pudo crear el Archivo Excel.');
  139. raise;
  140. end;
  141.  
  142. Columnas.Free;
  143. end;

Saludos.


  • 3

#2 sir.dev.a.lot

sir.dev.a.lot

    Advanced Member

  • Miembros
  • PipPipPip
  • 545 mensajes
  • Location127.0.0.1

Escrito 06 enero 2017 - 06:00


delphi
  1. function LPad(S: string; Ch: Char; Len: Integer): string;
  2. var RestLen: Integer;
  3. begin Result := S;
  4. RestLen := Len - Length(s);
  5. if RestLen < 1 then Exit;
  6. Result := S + StringOfChar(Ch, RestLen);
  7. end;
  8.  
  9. function RPad(S: string; Ch: Char; Len: Integer): string;
  10. var RestLen: Integer;
  11. begin Result := S;
  12. RestLen := Len - Length(s);
  13. if RestLen < 1 then Exit;
  14. Result := StringOfChar(Ch, RestLen) + S;
  15. end;

Para cual version de Delphi ?


delphi
  1. function LPad(Value: string; Key: Char = ' '; ALenght: Integer = 0): string;
  2. var
  3. iLen: Integer;
  4. begin
  5. iLen := Length(Value);
  6.  
  7. if (iLen > ALenght) then
  8. Result := Copy(Value, 1, ALenght)
  9. else
  10. Result := StringOfChar(Key, ALenght-iLen) + Value;
  11. end;
  12.  
  13. function LPad(Value: Integer; Key: Char = '0'; ALenght: Integer = 0): string;
  14. begin
  15. Result := LPad(IntToStr(Value), Key, ALenght);
  16. end;
  17.  
  18. function RPad(Value: string; Key: Char = ' '; ALenght: Integer = 0): string;
  19. var
  20. iLen: integer;
  21. begin
  22. iLen := Length(Value);
  23.  
  24. if (iLen > ALenght) then
  25. Result := Copy(Value, 1, ALenght)
  26. else
  27. Result := Value + StringOfChar(Key, ALenght-iLen);
  28. end;
  29.  
  30. function RPad(Value: integer; Key: Char = '0'; ALenght: Integer = 0): string;
  31. begin
  32. Result := RPad(IntToStr(Value), Key, ALenght);
  33. end;

Saludos!


  • 0

#3 Agustin Ortu

Agustin Ortu

    Advanced Member

  • Moderadores
  • PipPipPip
  • 831 mensajes
  • LocationArgentina

Escrito 07 enero 2017 - 01:08

...

 
 
Creo que te equivocaste de hilo  :D  :D

Editado por Agustin Ortu, 07 enero 2017 - 01:08 .

  • 0

#4 sir.dev.a.lot

sir.dev.a.lot

    Advanced Member

  • Miembros
  • PipPipPip
  • 545 mensajes
  • Location127.0.0.1

Escrito 07 enero 2017 - 04:48

 
 
Creo que te equivocaste de hilo  :D  :D

 

 

 

  • //Condicion
  • Libro.Cells[fila,6].NumberFormat := RPad('0', '0', Length(getCondicion(AData.FieldByName('INS_CONDICION').AsInteger)));
  • Libro.Cells[fila,6] := getCondicion(AData.FieldByName('INS_CONDICION').AsInteger);
  •  

 

Hola @

Agustin Ortu

 

La funcion RPad, esta en el Codigo de

enecumene

lo que no se si es una funcion que ya esta incluida en Berlin 10.1 o Tokyo, y escribi en mi POST Para cual version de Delphi ?

 

Saludos!


  • 0

#5 Marc

Marc

    Advanced Member

  • Moderadores
  • PipPipPip
  • 1.484 mensajes
  • LocationMallorca

Escrito 07 enero 2017 - 05:57

Este código solo funciona cuando Excel está instalado en el equipo, ¿ verdad ? (crea un objeto OLE Excel.Application).

 

Personalmente prefiero exportar a CSV, que es tremendamente fácil de hacer y no depende de tener aplicaciones instaladas. Además, Excel lee perfectamente esos archivos CSV.


  • 0

#6 enecumene

enecumene

    Webmaster

  • Administrador
  • 7.419 mensajes
  • LocationRepública Dominicana

Escrito 07 enero 2017 - 09:51

Este código solo funciona cuando Excel está instalado en el equipo, ¿ verdad ? (crea un objeto OLE Excel.Application).

 

Personalmente prefiero exportar a CSV, que es tremendamente fácil de hacer y no depende de tener aplicaciones instaladas. Además, Excel lee perfectamente esos archivos CSV.

 

Estás en lo cierto amigo Marc, así estaba en un principio, pero para el cliente le era tedioso utilizar el wizard de Excel al abrir arcivos CSV. 8o|

 

Saludos.


  • 0

#7 enecumene

enecumene

    Webmaster

  • Administrador
  • 7.419 mensajes
  • LocationRepública Dominicana

Escrito 07 enero 2017 - 09:52

Sir.Dev.A.Lot, RPAD y LPAD son funciones creadas fuera de delphi, hasta XE7 delphi no cuenta con funciones similares, no sabría decirte en las versiones más recientes.

 

Saludos.


  • 0

#8 sir.dev.a.lot

sir.dev.a.lot

    Advanced Member

  • Miembros
  • PipPipPip
  • 545 mensajes
  • Location127.0.0.1

Escrito 09 enero 2017 - 07:50

Lo he probado en Delphi 7 y Seattle y no lo tiene por defecto.

 

Pero si vi algo asi que es lo equivalente.


delphi
  1. program Project1;
  2. {$APPTYPE CONSOLE}
  3.  
  4. var
  5. strA, strB : String;
  6.  
  7. begin
  8. strA := '12345';
  9.  
  10. strB := strA.PadLeft(7);
  11.  
  12. Console.WriteLine('Default padding to 7 characters = ''' + strB + '''');
  13.  
  14. strB := strA.PadLeft(7, '-');
  15.  
  16. Console.WriteLine('Padding with ''-'' to 7 characters = ''' + strB + '''');
  17.  
  18. Console.ReadLine;
  19. end.

Inclui el RPAD y LPAD porque no lo vi en tu codigo @Enecumene.

 

Saludos!


  • 1

#9 enecumene

enecumene

    Webmaster

  • Administrador
  • 7.419 mensajes
  • LocationRepública Dominicana

Escrito 10 enero 2017 - 07:25

La verdad es que esa función se me coló ;)


  • 0

#10 enecumene

enecumene

    Webmaster

  • Administrador
  • 7.419 mensajes
  • LocationRepública Dominicana

Escrito 10 enero 2017 - 07:26

La verdad es que esa función se me coló ;)


  • 0

#11 Carlosgimenez

Carlosgimenez

    Newbie

  • Miembros
  • Pip
  • 3 mensajes

Escrito 18 julio 2022 - 08:42

Hay alguna manera de acelerar el proceso?? ya que cuando son muchos registros tarda su tiempo.. 


  • 0

#12 egostar

egostar

    missing my father, I love my mother.

  • Administrador
  • 14.446 mensajes
  • LocationMéxico

Escrito 18 julio 2022 - 04:05

Hay alguna manera de acelerar el proceso?? ya que cuando son muchos registros tarda su tiempo.. 

 

Hola Carlosgimenez

 

Lamentablemente el tiempo depende de los accesos a Excel, y el recorrido del Dataset por lo que el tiempo que tarda es exponencial.

 

 

Saludos


  • 0

#13 Carlosgimenez

Carlosgimenez

    Newbie

  • Miembros
  • Pip
  • 3 mensajes

Escrito 18 julio 2022 - 04:47

Hola Carlosgimenez

 

Lamentablemente el tiempo depende de los accesos a Excel, y el recorrido del Dataset por lo que el tiempo que tarda es exponencial.

 

 

Saludos

Ok. Perdon la pregunta. Soy nuevo en programación y sobre todo con Delphi. 


  • 0

#14 egostar

egostar

    missing my father, I love my mother.

  • Administrador
  • 14.446 mensajes
  • LocationMéxico

Escrito 18 julio 2022 - 06:17

Ok. Perdon la pregunta. Soy nuevo en programación y sobre todo con Delphi. 

 

Sin problema Carlosgimenez, bienvenido a DelphiAccess.-

 

Espero que seamos de ayuda, no dudes en preguntar, siempre habrá alguien que te pueda ayudar con gusto.

 

Saludos.


  • 0




IP.Board spam blocked by CleanTalk.