Comunidad Delphiaccess

Por favor ingresa o regístrate.

Ingresar con nombre de usuario, contraseña y duración de la sesión

Noticias y Eventos:




Autor Tema: Exportar de DBGrid a Excel  (Leído 2412 veces)

0 Usuarios y 1 Visitante están viendo este tema.

« en: 06 de Noviembre de 2008, 19:29:05 »
En línea

lKinGl

  • Administrador Adjunto
  • *******
  • Calificaciones: +2/-0
  • Desconectado Desconectado
  • Sexo: Masculino
  • Mensajes: 93
  • Gracias
  • -Dados: 0
  • -Recibidos: 0
  • KinGSoft
    • WWW
Exportar de DBGrid a Excel
« en: 06 de Noviembre de 2008, 19:29:05 »
Pasos para exportar de 1 DbGrid1 a Excel

1) En la Pestaña Servers Buscamos y agregamos un componente llamado TExcelApplication
2) Esta demás decir que ya debe estar lista la consulta Sql sin errores
3) Agregar a la Uses ComObj
4) Declaramos las siguientes variables:

Código: [Seleccionar]
Libro : _WORKBOOK;
Hoja : _WORKSHEET;
i:Integer;


5) agregamos este código dentro del begin y end del procedure, esta nos sirve para crear el archivo de excel sin Nombre, si le quieres poner nombre cambia Null por tu variable.

i nos manejará el número de filas


Código: [Seleccionar]
i:=0;
Libro := ExcelApplication1.Workbooks.Add(Null, 0);


6)luego agregamos esta nueva linea de código en donde elegimos en que Hoja vamos a trabajar

Código: [Seleccionar]
Hoja := Libro.Sheets[1] as _WORKSHEET;

7) Luego agregamos este código:


Código: [Seleccionar]
with Query1 do
begin
first;
while not EOF Do
begin
i:=i+1;
         Hoja.Cells.Item[i,1]:=DBGrid1.Fields[0].AsString;
         Hoja.Cells.Item[i,2]:=DBGrid1.Fields[1].AsString;
         Hoja.Cells.Item[i,3]:=DBGrid1.Fields[2].AsString;
         Hoja.Cells.Item[i,4]:=DBGrid1.Fields[3].AsString;
         Hoja.Cells.Item[i,5]:=DBGrid1.Fields[4].AsString;
         Hoja.Cells.Item[i,6]:='Bs.F '+DBGrid1.Fields[5].AsString;
         Hoja.Cells.Item[i,7]:='Bs.F '+DBGrid1.Fields[6].AsString;
         Hoja.Cells.Item[i,8]:=DBGrid1.Fields[7].AsString;
         Hoja.Cells.Item[i,9]:='Bs.F '+DBGrid1.Fields[8].AsString;
         Hoja.Cells.Item[i,10]:='Bs.F '+DBGrid1.Fields[9].AsString;
Next;
end;//while
end;//with


8) ahora pedimos que el libro que ahora está listo se abra y muestre los datos que agregamos


Código: [Seleccionar]
ExcelApplication1.Visible[1]:=true;

Aqui encontré la forma para exportar con bordes ;) cada a b c d e f g h i j es la columna y i es la fila al pasar por el for nos hace esto a*i  b*i  c*1 de esta manera todas las celdas quedan con el borde :P

Código: [Seleccionar]
  For b:=9 to i do
   begin
     Hoja.Range['a'+IntToStr(b),'a'+IntToStr(b)].BorderAround(xlContinuous,xlTransparent,xlAutomatic,EmptyParam);
     Hoja.Range['b'+IntToStr(b),'b'+IntToStr(b)].BorderAround(xlContinuous,xlTransparent,xlAutomatic,EmptyParam);
     Hoja.Range['c'+IntToStr(b),'c'+IntToStr(b)].BorderAround(xlContinuous,xlTransparent,xlAutomatic,EmptyParam);
     Hoja.Range['d'+IntToStr(b),'d'+IntToStr(b)].BorderAround(xlContinuous,xlTransparent,xlAutomatic,EmptyParam);
     Hoja.Range['e'+IntToStr(b),'e'+IntToStr(b)].BorderAround(xlContinuous,xlTransparent,xlAutomatic,EmptyParam);
     Hoja.Range['f'+IntToStr(b),'f'+IntToStr(b)].BorderAround(xlContinuous,xlTransparent,xlAutomatic,EmptyParam);
     Hoja.Range['g'+IntToStr(b),'g'+IntToStr(b)].BorderAround(xlContinuous,xlTransparent,xlAutomatic,EmptyParam);
     Hoja.Range['h'+IntToStr(b),'h'+IntToStr(b)].BorderAround(xlContinuous,xlTransparent,xlAutomatic,EmptyParam);
     Hoja.Range['i'+IntToStr(b),'i'+IntToStr(b)].BorderAround(xlContinuous,xlTransparent,xlAutomatic,EmptyParam);
     Hoja.Range['j'+IntToStr(b),'j'+IntToStr(b)].BorderAround(xlContinuous,xlTransparent,xlAutomatic,EmptyParam);
   end;
 

Nuestro código final nos queda asi:


Código: [Seleccionar]
procedure TForm5.BitBtn1Click(Sender: TObject);
var
Libro : _WORKBOOK;
Hoja : _WORKSHEET;
i,b:Integer;
begin
i:=10;
Libro := ExcelApplication1.Workbooks.Add(Null, 0);
Hoja := Libro.Sheets[1] as _WORKSHEET;
Hoja.Cells.Item[2,1]:=label16.Caption+' de '+label17.Caption;
Hoja.Cells.Item[3,1]:='R.I.F.: '+label19.Caption;
Hoja.Cells.Item[4,1]:='Libro de Ventas de '+label18.Caption;
Hoja.Cells.Item[2,1].font.size:=16;
Hoja.Cells.Item[3,1].font.size:=14;
Hoja.Cells.Item[4,1].font.size:=12;
Hoja.Cells.Item[10,1]:='Oper';
Hoja.Cells.Item[10,2]:='Fecha';
Hoja.Cells.Item[10,3]:='R.I.F.';
Hoja.Cells.Item[10,4]:='Nombre ó Razón Social';
Hoja.Cells.Item[9,5]:='Número de';
Hoja.Cells.Item[10,5]:='Factura';
Hoja.Cells.Item[9,6]:='Ventas';
Hoja.Cells.Item[10,6]:='Exentas';
Hoja.Cells.Item[9,7]:='Total';
Hoja.Cells.Item[10,7]:='Ventas';
Hoja.Cells.Item[10,8]:='I.V.A.';
Hoja.Cells.Item[9,9]:='Base';
Hoja.Cells.Item[10,9]:='Imponible';
Hoja.Cells.Item[9,10]:='Impuesto';
Hoja.Cells.Item[10,10]:='I.V.A.';
Hoja.Cells.Item[1,1].Font.Bold:=True;
Hoja.Cells.Item[10,1].Font.Bold:=True;
Hoja.Cells.Item[10,2].Font.Bold:=True;
Hoja.Cells.Item[10,3].Font.Bold:=True;
Hoja.Cells.Item[10,4].Font.Bold:=True;
Hoja.Cells.Item[9,5].Font.Bold:=True;
Hoja.Cells.Item[10,5].Font.Bold:=True;
Hoja.Cells.Item[9,6].Font.Bold:=True;
Hoja.Cells.Item[10,6].Font.Bold:=True;
Hoja.Cells.Item[9,7].Font.Bold:=True;
Hoja.Cells.Item[10,7].Font.Bold:=True;
Hoja.Cells.Item[10,8].Font.Bold:=True;
Hoja.Cells.Item[9,9].Font.Bold:=True;
Hoja.Cells.Item[10,9].Font.Bold:=True;
Hoja.Cells.Item[9,10].Font.Bold:=True;
Hoja.Cells.Item[10,10].Font.Bold:=True;
 with zQuery1 do
 begin
   first;
     while not EOF Do
       begin
         i:=i+1;
         Hoja.Cells.Item[i,1]:=DBGrid1.Fields[0].AsString;
         Hoja.Cells.Item[i,2]:=DBGrid1.Fields[1].AsString;
         Hoja.Cells.Item[i,3]:=DBGrid1.Fields[2].AsString;
         Hoja.Cells.Item[i,4]:=DBGrid1.Fields[3].AsString;
         Hoja.Cells.Item[i,5]:=DBGrid1.Fields[4].AsString;
         Hoja.Cells.Item[i,6]:='Bs.F '+DBGrid1.Fields[5].AsString;
         Hoja.Cells.Item[i,7]:='Bs.F '+DBGrid1.Fields[6].AsString;
         Hoja.Cells.Item[i,8]:=DBGrid1.Fields[7].AsString;
         Hoja.Cells.Item[i,9]:='Bs.F '+DBGrid1.Fields[8].AsString;
         Hoja.Cells.Item[i,10]:='Bs.F '+DBGrid1.Fields[9].AsString;
         Next;
       end;//while
 end;//with
 For b:=9 to i do
   begin
     Hoja.Range['a'+IntToStr(b),'a'+IntToStr(b)].BorderAround(xlContinuous,xlTransparent,xlAutomatic,EmptyParam);
     Hoja.Range['b'+IntToStr(b),'b'+IntToStr(b)].BorderAround(xlContinuous,xlTransparent,xlAutomatic,EmptyParam);
     Hoja.Range['c'+IntToStr(b),'c'+IntToStr(b)].BorderAround(xlContinuous,xlTransparent,xlAutomatic,EmptyParam);
     Hoja.Range['d'+IntToStr(b),'d'+IntToStr(b)].BorderAround(xlContinuous,xlTransparent,xlAutomatic,EmptyParam);
     Hoja.Range['e'+IntToStr(b),'e'+IntToStr(b)].BorderAround(xlContinuous,xlTransparent,xlAutomatic,EmptyParam);
     Hoja.Range['f'+IntToStr(b),'f'+IntToStr(b)].BorderAround(xlContinuous,xlTransparent,xlAutomatic,EmptyParam);
     Hoja.Range['g'+IntToStr(b),'g'+IntToStr(b)].BorderAround(xlContinuous,xlTransparent,xlAutomatic,EmptyParam);
     Hoja.Range['h'+IntToStr(b),'h'+IntToStr(b)].BorderAround(xlContinuous,xlTransparent,xlAutomatic,EmptyParam);
     Hoja.Range['i'+IntToStr(b),'i'+IntToStr(b)].BorderAround(xlContinuous,xlTransparent,xlAutomatic,EmptyParam);
     Hoja.Range['j'+IntToStr(b),'j'+IntToStr(b)].BorderAround(xlContinuous,xlTransparent,xlAutomatic,EmptyParam);
   end;
ExcelApplication1.Visible[1]:=true;
end;
 

Hoja.Cells.Item[fila,columna].font.size:=16; // para el tamaño de fuente de una celda
Hoja.Cells.Item[fila,columna].Font.Bold:=True; // para poner una celda en negrita

espero les guste y les sea util

Salu2

Cualquier duda o pregunta sobre este tutorial, puedes abrir un hilo en el foro adecuado.
« última modificación: 17 de Noviembre de 2008, 10:41:49 por enecumene »
Las cosas son o no son....
http://www.kingsoft.com.ve

«Responder #1 en: 18 de Diciembre de 2008, 23:38:58 »
En línea

vzavaletag

  • Registrado
  • *
  • Calificaciones: +0/-0
  • Desconectado Desconectado
  • Sexo: Masculino
  • Mensajes: 1
  • Gracias
  • -Dados: 0
  • -Recibidos: 0
Re: Exportar de DBGrid a Excel
« Respuesta #1 en: 18 de Diciembre de 2008, 23:38:58 »
Hola: :p
Esto esta exelente, me ayudastes bastante, ojala se pudiera darle color a las titulos y a las celdas.
Saludos.
 

«Responder #2 en: 19 de Diciembre de 2008, 04:43:03 »
En línea

coso

  • Usuario Activo
  • ***
  • Calificaciones: +1/-0
  • Desconectado Desconectado
  • Mensajes: 12
  • Gracias
  • -Dados: 0
  • -Recibidos: 0
Re: Exportar de DBGrid a Excel
« Respuesta #2 en: 19 de Diciembre de 2008, 04:43:03 »
Tambien se puede hacer asi

Código: [Seleccionar]
     q := TADOQuery.Create(nil);
    q.Connection := ADOConnection;
    q.Active := false;
    q.SQL.Text := 'select * into ["Excel 8.0;Database=c:\test.xls"].[tabla_uno] from tabla1';
    q.ExecSQL;
    q.Free;
 

en cuanto a la carga de datos


 


Página generada en 0.352 segundos con 31 consultas.