Foros Club Delphi

Foros Club Delphi (https://www.clubdelphi.com/foros/index.php)
-   C++ Builder (https://www.clubdelphi.com/foros/forumdisplay.php?f=13)
-   -   problemas con propiedades OLE de BCB6 a 2010 (https://www.clubdelphi.com/foros/showthread.php?t=87292)

lmpadron 09-12-2014 15:20:17

problemas con propiedades OLE de BCB6 a 2010
 
Saludos comunidad

Ya se como llamar a excel usando CreateObject pero al parecer eso no fue lo único que cambio del BCB6 al CodeGear 2010, el resto de mi código pude notar que no funciona, imagino que la forma de llamar a las propiedades de Excel no sea la misma, o sea el Item, Cells, etc... les dejo el código para que me ayuden a actualizarlo o me indiquen como hacerlo:

Código:

Variant Excel, Libro, Hoja, Celda;
Excel = Variant::CreateObject("Excel.Application");

Excel.OlePropertySet("Visible", false);
Libro = Excel.OlePropertyGet("Workbooks");
Libro.OleProcedure("Add");

Hoja = Libro.OlePropertyGet("Item", 1);
Libro = Hoja.OlePropertyGet("Worksheets");

char* Pepe= new char[ADOQuery7->FieldByName("Pepe")->Text.Length() + 10];
StrLCopy(Pepe,ADOQuery7->FieldByName("Pepe")->Text.c_str(),ADOQuery7->FieldByName("Pepe")->Text.Length());


Hoja.OlePropertyGet("Cells").OlePropertyGet("Item", 5, 1).OlePropertySet("Value", "Codigo");
Hoja.OlePropertyGet("Cells").OlePropertyGet("Item", 6, 1).OlePropertySet("Value", Pepe);

Celda = Hoja.OlePropertyGet("Cells").OlePropertyGet("Item", 5,1);
Celda.OlePropertyGet("Font").OlePropertySet("Bold", true);

Excel.OlePropertySet("DisplayAlerts", false);
Excel.OlePropertyGet("Workbooks").OlePropertyGet("Item", 1).OleProcedure("SaveAs", SaveDialog1->FileName.c_str());
Excel.OlePropertySet("Visible", true);
Excel = Unassigned;

ME devuleve el siguiente error

---------------------------
Debugger Exception Notification
---------------------------
Project Project1.exe raised exception class EOleSysError with message 'Nombre desconocido'.
---------------------------
Break Continue Help
---------------------------

Gracias de antemano por su tiempo

aguml 09-12-2014 18:09:57

¿En que linea te da el error? Si no lo sabes pon un bp en la primera, das a run y vas linea a linea con f8. Cuando yo vi este tema vi que al instalar microsoft office se añade un registro que identifica la version del office y que dependiendo de esta variaba la forma de crear el objeto ole, vamos la forma no, varia la cadena y puede ser ese tu error. A ver si puedo buscarlo. En la msdn hay muy buenos escritos para esto pero no recuerdo el nombre a buscar.

aguml 09-12-2014 22:54:08

Yo solo lo usé en C++Builder 6 y no para Excel pero te pongo lo que tengo por si te ayuda en algo.
Para Word:
Código PHP:

void __fastcall TForm1::ButtonExportToWordClick(TObject *Sender)
{
        
Variant WordApplication, vSelect, Shapes, ActiveDocument;
        
LPTSTR s;
        
int retval;
        
char valorDeLaClave[1024];

        
retval = LeerClaveRegistro(HKEY_CLASSES_ROOT, "Word.Application\\CurVer", "", valorDeLaClave);
        if(
retval != 0)
        {
                
retval = LeerClaveRegistro(HKEY_LOCAL_MACHINE, "SOFTWARE\\Classes\\Word.Application\\CurVer", "", valorDeLaClave);
                if(
retval != 0)
                {
                        
FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
                                      
FORMAT_MESSAGE_FROM_SYSTEM,
                                      
NULL,
                                      
retval,
                                      
0,
                                      (
LPTSTR)&s,
                                      
0,
                                      
NULL);
                        
MessageBoxA(Application->Handle, AnsiString("Huvo un error al obtener la clase de la version de Word.\n" + AnsiString(s)).c_str(), "Error", MB_OK | MB_ICONERROR | MB_APPLMODAL);
                        return;
                }
        }

        
SaveDialog->Filter = "Documento de Word (*.doc)|*.doc";
        
SaveDialog->FileName = "Diagramas.doc";
        if(
SaveDialog->Execute())
        {
                try
                {
                        
//WordApplication = CreateOleObject(valorDeLaClave);
                        
WordApplication = CreateOleObject("Word.Application");
                }
                catch(...)
                {
                        
MessageBox(Handle, "No se pudo iniciar el Word. ¿Está instalado?" , "Error", MB_OK |MB_ICONERROR | MB_APPLMODAL);
                        
WordApplication = Unassigned;
                        return;
                }
                
WordApplication.OlePropertySet("Visible", false);
                
WordApplication.OlePropertyGet("Documents").OleProcedure("Add");

                
ActiveDocument = WordApplication.OlePropertyGet("ActiveDocument");

                
vSelect = WordApplication.Exec(PropertyGet("Selection"));

                
//Reducimos los margenes poniendolos todos a 5
                
ActiveDocument.OlePropertyGet("PageSetup").OlePropertySet("TopMargin", 5);
                
ActiveDocument.OlePropertyGet("PageSetup").OlePropertySet("BottomMargin", 5);
                
ActiveDocument.OlePropertyGet("PageSetup").OlePropertySet("LeftMargin", 5);
                
ActiveDocument.OlePropertyGet("PageSetup").OlePropertySet("RightMargin", 5);

                
//Ponemos la alineacion horizontal en centrada
                
vSelect.OlePropertyGet("ParagraphFormat").OlePropertySet("Alignment", wdAlignParagraphCentre);

                
//Ponemos la alineacion vertica en centrada
                
ActiveDocument.OlePropertyGet("PageSetup").OlePropertySet("VerticalAlignment", wdAlignParagraphCentre);

                for(
int i = 0; i < CheckListBox->Count; i++)
                {
                        if(
CheckListBox->Checked[i] == true)
                        {

                                
/* Podemos hacerlo usando el portapapeles */

                                //Ponemos la imagen tildada en el TImage
                                //Image->Picture->LoadFromFile(ChangeFileExt(CheckListBox->Items->Strings[i], ".bmp"));

                                //La copiamos al portapapeles
                                //PopupMenu->Items->Items[0]->Click();

                                //Pegamos la imagen dentro del documento de Word
                                //vSelect.OleProcedure("Paste");

                                /* O podemos hacerlo usando AddPicture para añadir directamente el archivo de imagen */

                                
Shapes = vSelect.OlePropertyGet("InlineShapes");
                                
Shapes.OleFunction("AddPicture", AnsiString(ChangeFileExt(CheckListBox->Items->Strings[i], ".bmp")).c_str(), false, true);

                                
//Añadimos un salto de pagina cada vez que se añada una nueva imagen excepto cuando sea la ultima imagen
                                
if(i != CheckListBox->Count -1)
                                        
vSelect.OleFunction("InsertBreak", 0);

                                
Application->ProcessMessages();
                        }
                }

                
//Guardamos el archivo
                
AnsiString salida = ChangeFileExt(SaveDialog->FileName, ".doc");
                
ActiveDocument.OleProcedure("SaveAs", salida.c_str());

                
//Cerramos el Word
                
WordApplication.OleProcedure("Quit");

                
//Limpiamos las variables usadas
                
ActiveDocument.Clear();
                
WordApplication.Clear();
                
vSelect.Clear();
                
Shapes.Clear();
                
MessageBoxA(Application->Handle, "Imagenes exportadas satisfactoriamente.", "Información", MB_OK | MB_ICONINFORMATION | MB_APPLMODAL);
        }
} 

Para PowerPoint:
Código PHP:

void __fastcall TForm1::ButtonExportToPowerPointClick(TObject *Sender)
{
        
Variant PowerPointApp, Slide, Shapes, ActivePresentation;
        
LPTSTR s;
        
int retval;
        
char valorDeLaClave[1024];

        
retval = LeerClaveRegistro(HKEY_CLASSES_ROOT, "PowerPoint.Application\\CurVer", "", valorDeLaClave);
        if(
retval != 0)
        {
                
retval = LeerClaveRegistro(HKEY_LOCAL_MACHINE, "SOFTWARE\\Classes\\PowerPoint.Application\\CurVer", "", valorDeLaClave);
                if(
retval != 0)
                {
                        
FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
                                      
FORMAT_MESSAGE_FROM_SYSTEM,
                                      
NULL,
                                      
retval,
                                      
0,
                                      (
LPTSTR)&s,
                                      
0,
                                      
NULL);

                        
MessageBoxA(Application->Handle, AnsiString("Huvo un error al obtener la clase de la version de Word.\n" + AnsiString(s)).c_str(), "Error", MB_OK | MB_ICONERROR | MB_APPLMODAL);
                        return;
                }
        }

        
SaveDialog->Filter = "Presentacion de PowerPoint (*.ppt)|*.ppt";
        
SaveDialog->FileName = "Diagramas.ppt";
        if(
SaveDialog->Execute())
        {
                try
                {
                        
//PowerPointApp = CreateOleObject(valorDeLaClave);
                        
PowerPointApp = CreateOleObject("PowerPoint.Application");
                }
                catch(...)
                {
                        
MessageBox(Handle, "No se pudo iniciar el PowerPoint. ¿Está instalado?" , "Error", MB_OK |MB_ICONERROR  | MB_APPLMODAL);
                        
PowerPointApp = Unassigned;
                        return;
                }
                
PowerPointApp.OlePropertySet("Visible",true);

                
//Aqui está la presentacion activa
                
ActivePresentation = PowerPointApp.OlePropertyGet("Presentations").OleFunction("Add");

                
TImage *imagen = new TImage(Application);

                for(
int i = 0, contador = 1; i < CheckListBox->Count; i++)
                {
                        if(
CheckListBox->Checked[i] == true)
                        {
                                
//Aqui le decimos que queremos que la presentacion tenga tamaño Dim A4
                                
ActivePresentation.OlePropertyGet("PageSetup").OlePropertySet("SlideSize", ppSlideSizeA4Paper);

                                
//Aqui le decimos que la orientacion del papel será vertical
                                
ActivePresentation.OlePropertyGet("PageSetup").OlePropertySet("SlideOrientation",2);

                                
//Aqui creamos una pagina de la presentacion
                                
Slide = ActivePresentation.OlePropertyGet("Slides").OleFunction("Add",contador,12);

                                
contador++;

                                
//Abrimos la imagen en un TImage para poder obtener su ancho y su alto
                                
imagen->Picture->Bitmap->LoadFromFile(ChangeFileExt(CheckListBox->Items->Strings[i],".bmp"));

                                
//Metemos la imagen en el Shape
                                
Shapes = Slide.OlePropertyGet("Shapes").OleFunction("AddPicture", ChangeFileExt(CheckListBox->Items->Strings[i],".bmp").c_str(), false, true, 0, 0, imagen->Picture->Bitmap->Width, imagen->Picture->Bitmap->Height);

                                
//Ponemos el ajuste de la imagen para que se ajuste ancho y alto proporcionalmente
                                
Shapes.OlePropertySet("LockAspectRatio", true);

                                
//guardamos el ancho y alto de la imagen en dos variables
                                
int deltay = imagen->Picture->Bitmap->Height - MAXHEIGHTPP;
                                
int deltax = imagen->Picture->Bitmap->Width - MAXWIDTHPP;
                                
float porcentaje;

                                
//Averiguamos el ancho y alto apropiados para la imagen
                                
if(deltay > deltax && deltay > 0)
                                {
                                        
porcentaje = (100.0 * MAXHEIGHTPP) / imagen->Picture->Bitmap->Height;
                                        
Shapes.OlePropertySet("Width", imagen->Picture->Bitmap->Width - ((imagen->Picture->Bitmap->Width - (imagen->Picture->Bitmap->Width * porcentaje / 100))));
                                        
Shapes.OlePropertySet("Height", imagen->Picture->Bitmap->Height - ((imagen->Picture->Bitmap->Height - (imagen->Picture->Bitmap->Height * porcentaje / 100))));
                                }
                                else if(
deltax > deltay && deltax > 0)
                                {
                                        
porcentaje = (100.0 * MAXWIDTHPP) / imagen->Picture->Bitmap->Width;
                                        
Shapes.OlePropertySet("Width", imagen->Picture->Bitmap->Width - ((imagen->Picture->Bitmap->Width - (imagen->Picture->Bitmap->Width * porcentaje / 100))));
                                        
Shapes.OlePropertySet("Height", imagen->Picture->Bitmap->Height - ((imagen->Picture->Bitmap->Height - (imagen->Picture->Bitmap->Height * porcentaje / 100))));
                                }
                                
//Si la imagen tiene un ancho y alto inferiores al maximo no hace falta ajustarlos

                                //Recuperamos el ancho y alto de la imagen en la presentacion
                                
deltay = Shapes.OlePropertyGet("Height");
                                
deltax = Shapes.OlePropertyGet("Width");

                                
//Calculamos la posicion Left y Top
                                
int posX = (MAXWIDTHPP - deltax) / 2;
                                
int posY = (MAXHEIGHTPP - deltay) / 2;

                                
//Posicionamos la imagen centrada
                                
Shapes.OlePropertySet("Top", posY);
                                
Shapes.OlePropertySet("Left", posX);

                                
Application->ProcessMessages();
                        }
                }

                
//Guardamos el archivo
                
AnsiString salida = ChangeFileExt(SaveDialog->FileName, ".ppt");
                
SaveDialog->FileName = salida;
                
ActivePresentation.OleProcedure("SaveAs", salida.c_str());

                
//Cerramos el Word
                
PowerPointApp.OleProcedure("Quit");

                
//Limpiamos las variables usadas
                
ActivePresentation.Clear();
                
PowerPointApp.Clear();
                
Slide.Clear();
                
Shapes.Clear();

                
delete(imagen);
                
MessageBoxA(Application->Handle, "Imagenes exportadas satisfactoriamente.", "Información", MB_OK | MB_ICONINFORMATION | MB_APPLMODAL);
        }
} 

Y esta es la funcion que me creé para leer la clave de registro y saber si estaba insalado el office:
Código PHP:

int LeerClaveRegistro(HKEY hKey, char *clave, char *nombreClave, char *valorDeLaClave)
{
        
unsigned char infoValor[1024];
        
HKEY phkResult;
        
LONG IStatus;
        
DWORD dwType=REG_SZ;
        
DWORD dwSize=1023;
        
LPTSTR s;

        
IStatus = RegOpenKeyEx(hKey, clave, 0, KEY_READ, &phkResult);
        if(
IStatus == ERROR_SUCCESS)
        {
                
IStatus = RegQueryValueEx(phkResult,nombreClave,0,&dwType,(LPBYTE)&infoValor,&dwSize);
                if(
IStatus == ERROR_SUCCESS)
                {
                        
strcpy(valorDeLaClave, infoValor);
                        
RegCloseKey(phkResult);
                }
        }
        
/*FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
                      FORMAT_MESSAGE_FROM_SYSTEM,
                      NULL,
                      IStatus,
                      0,
                      (LPTSTR)&s,
                      0,
                      NULL);
        MessageBoxA(Application->Handle, s, "Error", MB_OK | MB_ICONERROR | MB_APPLMODAL); */
        
return IStatus;
} 

Una cosa que veo que no haces es liberar al objeto al terminar con "Quit". No se si esto funcionaría tal cual en la 2010 pero en la 6 va como la seda.
Al leer el registro obtienes la version y si no está instalado pues lo sabrás tambien.


La franja horaria es GMT +2. Ahora son las 20:26:15.

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2026, Jelsoft Enterprises Ltd.
Traducción al castellano por el equipo de moderadores del Club Delphi