Club Builder - Foros de discusión Club Builder
Foro de C++Builder en español
 
 FAQFAQ   BuscarBuscar   MiembrosMiembros   Grupos de UsuariosGrupos de Usuarios   RegistrarseRegistrarse 
 PerfilPerfil   Entra para ver tus mensajes privadosEntra para ver tus mensajes privados   EntrarEntrar 

Generar Excel con DataSet o con StringGrid

 
Publicar nuevo tema   Responder al tema    Foros de discusión -> Tips & Tricks
Ver tema anterior :: Ver tema siguiente  
Autor Mensaje
Mensaje    Asunto: Generar Excel con DataSet o con StringGrid Responder citando

Hola a todos,

Os paso unas funciones para que podais exportar a Excel con DataSet o con StringGrid, he dado mil vueltas para conseguir hacerlo osea que os lo resumo y asi lo teneis más facil.

Lo he sacado de buscar mucho por el foro y sacar codigo de aqui y finalmente con la ayuda de Juanma que ha sido el que me ayudo a ver la luz, gracias Juanma por tu ayuda.

Esta primera funcion es para el DataSet, lo pasais como parametro y listo.

********************************************
#pragma option push -Od
void __fastcall TFMain::GeneraExcelDB( TDataSet *DataSet)
{
//-------- Abre EXCEL
Variant xlApp;
xlApp = CreateOleObject("Excel.Application");
Variant xlBooks = xlApp.OlePropertyGet("Workbooks"); //-------- crea acceso al objeto 'libro'/workbook
xlBooks.OleProcedure("Add"); //-------- Crea un fichero nuevo
Variant xlBook = xlBooks.OlePropertyGet("Item", 1); //-------- coge el primer libro de la aplicacion
Variant xlSheets = xlBook.OlePropertyGet("Worksheets"); //-------- crea acceso al objeto 'hoja'/worksheets
Variant xlSheet = xlSheets.OlePropertyGet("Item", 1);//-------- coge la primera hoja del libro
//-------- Trabajando con celdas...
//-------- Escribe titulos (nombres de campos)
AnsiString LETRA = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
for(int i = 0; i <DataSet>FieldCount; i++)
{
Variant VRange;
AnsiString celda = LETRA.SubString(i+1,1);
VRange = xlSheet.OlePropertyGet("Columns",celda.c_str());
Variant ColumnWidth=DataSet->Fields->Fields[i]->DisplayWidth;
VRange.OlePropertySet("ColumnWidth",ColumnWidth);

celda = celda+IntToStr(1);
VRange = xlSheet.OlePropertyGet("Range",celda.c_str());
VRange.OlePropertySet("Value",DataSet->Fields->Fields[i]->FieldName);
}

int fila = 3;
DataSet->First();
while( !DataSet->Eof )
{
for(int i = 0; i <DataSet>FieldCount; i++)
{
Variant VRange;
AnsiString celda = LETRA.SubString(i+1,1)+IntToStr(fila);
VRange = xlSheet.OlePropertyGet("Range",celda.c_str());
VRange.OlePropertySet("Value",DataSet->Fields->Fields[i]->AsString.c_str() );
}
DataSet->Next();
++fila;
}
DataSet->First();
xlApp.OlePropertySet("Visible", true); //-------- hace EXCEL visible
xlApp.Clear();
}
#pragma option pop
********************************************
Esta segunda funcion es muy parecida pero en vez de hacerlo con un DataSet lo hace con un StringGrid, lo mismo lo pasais como parametro y arreglado.

********************************************
#pragma option push -Od
void __fastcall TFMain::GeneraExcelSG(TStringGrid *StringGrid)
{
//-------- Abre EXCEL
Variant xlApp;
xlApp = CreateOleObject("Excel.Application");
Variant xlBooks = xlApp.OlePropertyGet("Workbooks"); //-------- crea acceso al objeto 'libro'/workbook
xlBooks.OleProcedure("Add"); //-------- Crea un fichero nuevo
Variant xlBook = xlBooks.OlePropertyGet("Item", 1); //-------- coge el primer libro de la aplicacion
Variant xlSheets = xlBook.OlePropertyGet("Worksheets"); //-------- crea acceso al objeto 'hoja'/worksheets
Variant xlSheet = xlSheets.OlePropertyGet("Item", 1);//-------- coge la primera hoja del libro
//-------- Trabajando con celdas...
//-------- Escribe titulos (nombres de campos)
AnsiString LETRA = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
for(int n = 0; n <StringGrid>RowCount; n++)
{
for(int i = 0; i <StringGrid>ColCount; i++)
{
Variant VRange;
AnsiString celda = LETRA.SubString(i+1,1)+IntToStr(n+1);
VRange = xlSheet.OlePropertyGet("Range",celda.c_str());
VRange.OlePropertySet("Value",StringGrid->Cells[i][n].c_str());
}
}
xlApp.OlePropertySet("Visible", true); //-------- hace EXCEL visible
xlApp.Clear();
}
#pragma option pop
********************************************

Pues nada, espero que os valga este resumen que he ido sacando del foro, sinceramente este foro es un pozo de sabiduria, cualquier cosa que uno quiere hacer aqui lo tiene.

Un abrazo a todos.

Carlos
Volver arriba
Ver perfil de usuario Enviar mensaje privado Enviar email
Mensaje    Asunto: no me funciona Responder citando

me interesa mucho el codigo para pasar datos de un stringgrid a excel pero me dice:

Qualifier 'TFMain' is not a class or namespace name

espero tu respuesta
Volver arriba
Ver perfil de usuario Enviar mensaje privado
Mensaje    Asunto: Responder citando

Te cuento,

TFMain es el formulario principal donde yo pongo la funcion, tu deberias poner en vez de TFMain donde hayas puesto la funcion, por ejemplo en la funcion pone:

void __fastcall TFMain::GeneraExcelDB( TDataSet *DataSet)

Imaginemos que tu tienes un formulario que se llama Funciones, pues deberias poner:

void __fastcall Funciones::GeneraExcelDB( TDataSet *DataSet)

Entiendes? imagino que este es el problema por el que te da el error, prueba como te digo a ver si te funciona.

Un abrazo.

Carlos
Volver arriba
Ver perfil de usuario Enviar mensaje privado Enviar email
Mensaje    Asunto: Error Responder citando

Encontre el error que me sale:
es en sysvari.h (????)
Undefined symbol TAutoArgs

En una línea que dice:
TAtutoArgs<1> args;

Gracias, espero tu respuesta
Volver arriba
Ver perfil de usuario Enviar mensaje privado
Mensaje    Asunto: Responder citando

Hola a todos,

Parece ser que este código no funciona con Excel 2013, sabéis por que? no termino de encontrar la razón.

Un abrazo.

Carlos
_________________
Carlos J. Fernandez
Volver arriba
Ver perfil de usuario Enviar mensaje privado Enviar email
Mensaje    Asunto: Responder citando

Carlos J. Fernandez escribió:
Parece ser que este código no funciona con Excel 2013, sabéis por que? no termino de encontrar la razón.

Con unos pequeños cambios me funciona en la versión 2013, y también debería de funcionar en las anteriores:

Código:
void __fastcall GeneraExcelDB(TDataSet *DataSet)
{
    // -------- Abre EXCEL
    Variant xlApp = CreateOleObject("Excel.Application");
    Variant xlBooks = xlApp.OlePropertyGet("Workbooks");
    // -------- crea acceso al objeto 'libro'/workbook
    xlBooks.OleProcedure("Add"); // -------- Crea un fichero nuevo
    Variant xlBook = xlBooks.OlePropertyGet("Item", 1);
    // -------- coge el primer libro de la aplicacion
    Variant xlSheets = xlBook.OlePropertyGet("Worksheets");
    // -------- crea acceso al objeto 'hoja'/worksheets
    Variant xlSheet = xlSheets.OlePropertyGet("Item", 1);
    // -------- coge la primera hoja del libro
    // -------- Trabajando con celdas...
    // -------- Escribe titulos (nombres de campos)
    WideString LETRA = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    for (int i = 0; i < DataSet->FieldCount; i++)
    {
        WideString celda = LETRA.SubString(i + 1, 1);
        Variant VRange = xlSheet.OlePropertyGet("Columns", celda);
        Variant ColumnWidth = DataSet->Fields->Fields[i]->DisplayWidth;
        VRange.OlePropertySet("ColumnWidth", ColumnWidth);

        celda = celda + IntToStr(1);
        VRange = xlSheet.OlePropertyGet("Range", celda);
        VRange.OlePropertySet("Value", WideString(DataSet->Fields->Fields[i]->FieldName));
    }

    int fila = 3;
    DataSet->First();
    while (!DataSet->Eof)
    {
        for (int i = 0; i < DataSet->FieldCount; i++)
        {
            Variant VRange;
            WideString celda = LETRA.SubString(i + 1, 1) + IntToStr(fila);
            VRange = xlSheet.OlePropertyGet("Range", celda);
            VRange.OlePropertySet("Value", WideString(DataSet->Fields->Fields[i]->AsString));
        }
        DataSet->Next();
        ++fila;
    }
    DataSet->First();
    xlApp.OlePropertySet("Visible", true); // -------- hace EXCEL visible
    xlApp.Clear();
}

Código:
void __fastcall GeneraExcelSG(TStringGrid *StringGrid)
{
    // -------- Abre EXCEL
    Variant xlApp = CreateOleObject("Excel.Application");
    Variant xlBooks = xlApp.OlePropertyGet("Workbooks");
    // -------- crea acceso al objeto 'libro'/workbook
    xlBooks.OleProcedure("Add"); // -------- Crea un fichero nuevo
    Variant xlBook = xlBooks.OlePropertyGet("Item", 1);
    // -------- coge el primer libro de la aplicacion
    Variant xlSheets = xlBook.OlePropertyGet("Worksheets");
    // -------- crea acceso al objeto 'hoja'/worksheets
    Variant xlSheet = xlSheets.OlePropertyGet("Item", 1);
    // -------- coge la primera hoja del libro
    // -------- Trabajando con celdas...
    // -------- Escribe titulos (nombres de campos)
    WideString LETRA = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

    for (int n = 0; n < StringGrid->RowCount; n++)
    {
        for (int i = 0; i < StringGrid->ColCount; i++)
        {
            WideString celda = LETRA.SubString(i + 1, 1) + IntToStr(n + 1);
            Variant VRange = xlSheet.OlePropertyGet("Range", celda);
            VRange.OlePropertySet("Value", WideString(StringGrid->Cells[i][n]));
        }
    }
    xlApp.OlePropertySet("Visible", true); // -------- hace EXCEL visible
    xlApp.Clear();
}
Volver arriba
Ver perfil de usuario Enviar mensaje privado
Mensaje    Asunto: Responder citando

Estupendo Leo,

Voy a probarlo con los dos Excel a ver si va todo bien.

Un abrazo y gracias de nuevo.

Carlos
_________________
Carlos J. Fernandez
Volver arriba
Ver perfil de usuario Enviar mensaje privado Enviar email
Mensaje    Asunto: Responder citando

Leo,

Tengo un problemilla, cuando la base de datos tiene muchos campos da un error, tengo la impresión de que el problema viene de esta linea:

WideString LETRA = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

Los primeros campos muy bien, pero cuando llega al que va después de la "Z" que en Excel seria "AA" es cuando da el problema.

Se te ocurre algo rápido? o simplemente añado más letras en la variable y ya esta?

Tipo esto:

WideString LETRA = "ABCDEFGHIJKLMNOPQRSTUVWXYZAAAB";

Lo que pasa es que serian dos letras las que tiene que leer en vez de una no?

Un abrazo.

Carlos
_________________
Carlos J. Fernandez
Volver arriba
Ver perfil de usuario Enviar mensaje privado Enviar email
Mensaje    Asunto: Responder citando

Carlos J. Fernandez escribió:
Tengo un problemilla, cuando la base de datos tiene muchos campos da un error, tengo la impresión de que el problema viene de esta linea:

WideString LETRA = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

Los primeros campos muy bien, pero cuando llega al que va después de la "Z" que en Excel seria "AA" es cuando da el problema.


Prueba así a ver:

Código:
void __fastcall GeneraExcelDB(TDataSet *DataSet)
{
    Variant xlApp   = CreateOleObject("Excel.Application");
    Variant xlBook  = xlApp.OlePropertyGet("Workbooks").OleFunction("Add");
    Variant xlSheet = xlBook.OlePropertyGet("Worksheets").OlePropertyGet("Item", 1);

    for (int i = 0; i < DataSet->FieldCount; ++i)
    {
        Variant VRange = xlSheet.OlePropertyGet("Columns", i + 1);
        VRange.OlePropertySet("ColumnWidth",
            DataSet->Fields->Fields[i]->DisplayWidth);
        xlSheet.OlePropertySet("Cells", 1, i+1,
            WideString(DataSet->Fields->Fields[i]->FieldName));
    }

    int fila = 3;
    DataSet->First();
    while (!DataSet->Eof)
    {
        for (int i = 0; i < DataSet->FieldCount; ++i)
        {
            xlSheet.OlePropertySet("Cells", fila, i + 1,
                WideString(DataSet->Fields->Fields[i]->AsString));
        }
        DataSet->Next();
        ++fila;
    }
    DataSet->First();

    xlApp.OlePropertySet("Visible", true);
    xlApp.Clear();
}

Código:
void __fastcall GeneraExcelSG(TStringGrid *StringGrid)
{
  Variant xlApp   = CreateOleObject("Excel.Application");
  Variant xlBook  = xlApp.OlePropertyGet("Workbooks").OleFunction("Add");
  Variant xlSheet = xlBook.OlePropertyGet("Worksheets").OlePropertyGet("Item", 1);

  for (int y = 0; y < StringGrid->RowCount; ++y)
    for (int x = 0; x < StringGrid->ColCount; ++x)
      xlSheet.OlePropertySet("Cells", y+1, x+1, WideString(StringGrid->Cells[x][y]));

  xlApp.OlePropertySet("Visible", true);
  xlApp.Clear();
}
Volver arriba
Ver perfil de usuario Enviar mensaje privado
Mensaje    Asunto: Responder citando

Leo,

Estupendo, todo perfecto, lo he probado en Excel 2010 y 2013 y funciona perfecto.

Muchas gracias como siempre Leo.

Un abrazo.

Carlos
_________________
Carlos J. Fernandez
Volver arriba
Ver perfil de usuario Enviar mensaje privado Enviar email
Mensaje    Asunto: Responder citando

Código:
void __fastcall GeneraExcelSG(TStringGrid *StringGrid)
{
  Variant xlApp   = CreateOleObject("Excel.Application");
  Variant xlBook  = xlApp.OlePropertyGet("Workbooks").OleFunction("Add");
  Variant xlSheet = xlBook.OlePropertyGet("Worksheets").OlePropertyGet("Item", 1);

  for (int y = 0; y < StringGrid->RowCount; ++y)
    for (int x = 0; x < StringGrid->ColCount; ++x)
      xlSheet.OlePropertySet("Cells", y+1, x+1, WideString(StringGrid->Cells[x][y]));

  xlApp.OlePropertySet("Visible", true);
  xlApp.Clear();
}


siempre utilice este código y me funciona perfectamente pero ahora al generar un excel desde un StringGrid deseo guardarlo automaticamente:

agregando:
Código:
  AnsiString x=ExtractFilePath(Application->ExeName)+Now().FormatString("yyyymmdd")+Now().FormatString("hhmmss")+".xls";
  xlApp.OleFunction("save", WideString(x.c_str()));
xlApp.OleProcedure("Save");


pero nada no me hace nada...
hay un codigo de Leo en https://cppbuilder.es/viewtopic.php?t=13773&highlight=widestring pero no logro hacerlo funcionar con el código de arriba... alguna sugerencia? gracias de antemano.
_________________
><(((((º> From °l||l° §ÂN ÅNЮ€$ i§Lã$ °l||l°
_____________________
Volver arriba
Ver perfil de usuario Enviar mensaje privado Enviar email Visitar sitio web del autor MSN Messenger
Mensaje    Asunto: Responder citando

Buenas tardes!

Código:
void __fastcall GeneraExcelSG(TStringGrid *StringGrid)
{
  Variant xlApp   = CreateOleObject("Excel.Application");
  Variant xlBook  = xlApp.OlePropertyGet("Workbooks").OleFunction("Add");
  Variant xlSheet = xlBook.OlePropertyGet("Worksheets").OlePropertyGet("Item", 1);

  for (int y = 0; y < StringGrid->RowCount; ++y)
    for (int x = 0; x < StringGrid->ColCount; ++x)
      xlSheet.OlePropertySet("Cells", y+1, x+1, WideString(StringGrid->Cells[x][y]));

  xlApp.OlePropertySet("Visible", true);
  xlApp.Clear();
}


siempre utilice este código y me funciona perfectamente pero ahora al generar un excel desde un StringGrid deseo guardarlo automaticamente:

agregando:
Código:
  AnsiString x=ExtractFilePath(Application->ExeName)+Now().FormatString("yyyymmdd")+Now().FormatString("hhmmss")+".xls";
  xlApp.OleFunction("save", WideString(x.c_str()));
xlApp.OleProcedure("Save");


pero nada no me hace nada...
hay un codigo de Leo en https://cppbuilder.es/viewtopic.php?t=13773&highlight=widestring pero no logro hacerlo funcionar con el código de arriba... alguna sugerencia? gracias de antemano.
_________________
><(((((º> From °l||l° §ÂN ÅNЮ€$ i§Lã$ °l||l°
_____________________
Volver arriba
Ver perfil de usuario Enviar mensaje privado Enviar email Visitar sitio web del autor MSN Messenger
Mensaje    Asunto: Responder citando

A mi me da error (call to undefined function createoleobject) y antes no me lo daba. Una ayudita?
_________________
¡ADELANTE CON ESTE SUPER FORO!
Volver arriba
Ver perfil de usuario Enviar mensaje privado
Mostrar mensajes de anteriores:   
Cambiar a:  
No puedes publicar temas nuevos en este foro
No puedes responder a temas en este foro
No puedes editar tus mensajes en este foro
No puedes borrar tus mensajes en este foro
No puedes votar en las encuestas de este foro


Hosting WordPress Indedmedia desde 3,99 €
© 2002–2026 Club Builder · Funciona con phpBB.