 |
Club Builder Foro de C++Builder en español
|
| Ver tema anterior :: Ver tema siguiente |
| Autor |
Mensaje |
Carlos J. Fernandez Master


Registrado: 27 Oct 2004Mensajes: 574
|
Publicado: Lun 28 Abr, 2008 11:22 am Asunto: Generar Excel con DataSet o con StringGrid |
|
|
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 |
|
 |
soylacomadreja Cdt

Registrado: 11 Jul 2008Mensajes: 3
|
Publicado: Sab 12 Jul, 2008 6:13 pm Asunto: no me funciona |
|
|
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 |
|
 |
Carlos J. Fernandez Master


Registrado: 27 Oct 2004Mensajes: 574
|
Publicado: Sab 12 Jul, 2008 7:23 pm Asunto: |
|
|
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 |
|
 |
migue_1988 Cdt

Registrado: 26 Nov 2008Mensajes: 19
|
Publicado: Sab 06 Dic, 2008 6:16 pm Asunto: Error |
|
|
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 |
|
 |
Carlos J. Fernandez Master


Registrado: 27 Oct 2004Mensajes: 574
|
Publicado: Mar 09 Jul, 2013 2:51 pm Asunto: |
|
|
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 |
|
 |
_Leo Site Admin

Registrado: 11 Ago 2002Mensajes: 1875Ubicación: Lanzarote - Islas Canarias (España)
|
Publicado: Mie 10 Jul, 2013 5:29 am Asunto: |
|
|
| 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 |
|
 |
Carlos J. Fernandez Master


Registrado: 27 Oct 2004Mensajes: 574
|
Publicado: Mie 10 Jul, 2013 12:12 pm Asunto: |
|
|
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 |
|
 |
Carlos J. Fernandez Master


Registrado: 27 Oct 2004Mensajes: 574
|
Publicado: Mie 10 Jul, 2013 3:17 pm Asunto: |
|
|
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 |
|
 |
_Leo Site Admin

Registrado: 11 Ago 2002Mensajes: 1875Ubicación: Lanzarote - Islas Canarias (España)
|
Publicado: Mie 10 Jul, 2013 8:41 pm Asunto: |
|
|
| 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 |
|
 |
Carlos J. Fernandez Master


Registrado: 27 Oct 2004Mensajes: 574
|
Publicado: Jue 11 Jul, 2013 12:31 pm Asunto: |
|
|
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 |
|
 |
likibuay Master


Registrado: 24 Abr 2006Mensajes: 190Ubicación: COLOMBIA
|
Publicado: Mar 03 Feb, 2015 11:23 pm Asunto: |
|
|
| 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 |
|
 |
likibuay Master


Registrado: 24 Abr 2006Mensajes: 190Ubicación: COLOMBIA
|
Publicado: Mar 03 Feb, 2015 11:24 pm Asunto: |
|
|
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 |
|
 |
Tugui Master


Registrado: 09 Nov 2002Mensajes: 663
|
Publicado: Vie 17 Abr, 2015 3:22 pm Asunto: |
|
|
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 |
|
 |
|
|
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
|
© 2002–2026 Club Builder · Funciona con phpBB.
|