Hola, estoy intentando exportar datos de una consulta a una hoja excel, pero me da error, este es el código que utilizo:
Código PHP:
void __fastcall exportarAExcel(TADOQuery *q,String hoja,String fichero)
{
Variant _excel;
Variant _libro;
Variant _hoja;
Variant _celda;
Variant aux = NULL;
String txt = "";
int fila = 1;//me almacena en qué fila del Excel estoy escribiendo
int columna = 1;//me almacena en qué columna del Excel estoy escribiendo
try{
_excel = CreateOleObject("Excel.Application");
//doy valor al libro a partir de la aplicación: su libro
_libro = _excel.OlePropertyGet("Workbooks");
//le digo lo que tiene que hacer: añadir hojas
_libro.OleProcedure("Add");
//asigno a la hoja el primer item del libro
_hoja = _libro.OlePropertyGet("Item",1);
//
_libro = _hoja.OlePropertyGet("Worksheets");
//Libro=Hoja.OlePropertyGet("Worksheets");
_libro.OlePropertyGet("Item",1).OlePropertySet("Name",hoja);
//RECORRO LA CONSULTA INSERTANDO LAS CELDAS
_hoja = _libro.OlePropertyGet("Item",1);
//primero relleno las cabeceras: LA PRIMERA FILA (letra en blanco negrita y fondo negro)
for(columna = 1; columna <= q->Fields->Count;columna++){
txt = q->Fields->Fields[columna-1]->FieldName;
_hoja.OlePropertyGet("Cells").OlePropertyGet("Item",fila,columna).OlePropertySet("Value",txt );
_hoja.OlePropertyGet("Cells").OlePropertyGet("Item",fila,columna).OlePropertyGet("Font").OlePropertySet("Color",clBlack);
_hoja.OlePropertyGet("Cells").OlePropertyGet("Item",fila,columna).OlePropertyGet("Font").OlePropertySet("Bold",true);
_hoja.OlePropertyGet("Cells").OlePropertyGet("Item",fila,columna).OlePropertyGet("Interior").OlePropertySet("ColorIndex",clBlack);
}
fila = 2;
while( !q->Eof ){
for(columna = 1; columna <= q->Fields->Count;columna++){
txt = q->Fields->Fields[columna-1]->AsString;
_hoja.OlePropertyGet("Cells").OlePropertyGet("Item",fila,columna).OlePropertySet("Value",txt );
//vuelvo a empezar desde la primera columna: COLUMNA = 1
}
q->Next();//avanzo al siguiente registro: cambio de línea
fila++;
}
_excel.OlePropertySet("DisplayAlerts",false); //suppress the warning dialog on closing the server
//_excel.OlePropertyGet("Workbooks").OlePropertyGet("Item",1).OleProcedure("SaveAs",fichero);
//la pongo en visible
_excel.OlePropertySet("Visible",true);
//_excel.OleProcedure("Quit");
//_excel = Unassigned;
}
catch(Exception *e){
_excel.OlePropertySet("DisplayAlerts",false); //suppress the warning dialog on closing the server
_excel.OleProcedure("Quit");
_excel = Unassigned;
}
}
¿Me podría ayudar?
Gracias!!