Mensaje    Asunto: pequeño resumen de utilizacion de excel Responder citando

// Resumen de importación / exportación de ficheros excel
//
// funciones básicas (no se más)


//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#include <vcl.h>

#include <dos.h> // para _sleep()
#include <stdio.h> // para sprintf()
#pragma hdrstop

#include "pro2.h"


//
// librerias necesarias para trabajar con excel
//

#include<ComObj.hpp>


//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;

//
// variables globales
//


Variant aplicacionExcel; // objeto OLE tipo ExcelApplication
Variant coleccionLibros; // coleción de libros del objeto AplicacionExcel
Variant coleccionHojas; // coleción de hojas de un objeto libro
Variant libro; // un libro de la coleccion de libros
Variant hoja; // una hoja de la colección de hojas
Variant celdas; // coleccion de celdas

String mensajeAlerta="Hay un fichero abierto! NO CERRAR LA APLICACIÓN";


//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
: TForm(Owner)
{
limpiarFormulario();

}
//---------------------------------------------------------------------------
void __fastcall TForm1::cerrarExcel()
{
// cerrar el excel

aplicacionExcel.Exec(PropertySet("Visible")<<false);
aplicacionExcel.Exec(Procedure("Quit"));
aplicacionExcel.Clear();

limpiarFormulario();
}

//---------------------------------------------------------------------------
void __fastcall TForm1::limpiarFormulario()
{
EnombreFichero->Clear();
EnumHojas->Clear();
EnombreHoja->Clear();
EprimeraCelda->Clear();
EultimaCelda->Clear();
EnumFilas->Clear();
EnumCols->Clear();
Efila->Clear();
Ecolumna->Clear();
EvalorString->Clear();
EvalorInt->Clear();
EvalorChar->Clear();

Panel1->Color=clBtnShadow;
Pabierto->Color=clBtnFace;
Pabierto->Caption="";
}


//---------------------------------------------------------------------------
//-------------------- Importar un archivo de Excel ---------------------
//---------------------------------------------------------------------------

void __fastcall TForm1::BimportarExcelClick(TObject *Sender)
{
BimportarExcel->Enabled=false;
BexportarExcel->Enabled=false;
//
// Empezamos con EXCEL
//

OpenDialog1->Title="Importar datos de";

if (OpenDialog1->Execute())
{
//Busco un fichero Excel y obtengo su nombre y ruta
Variant FileName = OpenDialog1->FileName.c_str();
EnombreFichero->Text=FileName;

try
{
Pabierto->Color=clYellow;
Pabierto->Caption=mensajeAlerta;
//Abro la aplicación Excel y la hago visible
aplicacionExcel=CreateOleObject("Excel.Application");
//aplicacionExcel.Exec(PropertySet("Visible")<<true);

//
// LIBROS
//

// coger el primer objeto libro de la colección
coleccionLibros=aplicacionExcel.Exec(PropertyGet("Workbooks"));
// abrirlo
coleccionLibros.Exec(Procedure("Open")<<OpenDialog1->FileName);

/*
// (sin usar el OpenDialog)
// coleccionLibros.Exec(Procedure("Open") << "C:\\directorio\\fichero.xls");
*/
}
catch (Exception &exception) // no llegó a abrirse
{
Application->MessageBox(
"Esta aplicación necesita Excel 97 o superior",
"Aviso...",MB_ICONSTOP);
BimportarExcel->Enabled=true;
BexportarExcel->Enabled=true;
return;
}

try
{
//
// LIBRO ACTIVO
//

// coger el primer libro de la aplicacion
libro = coleccionLibros.Exec(PropertyGet("Item") << 1);



//
// HOJAS
//

// coger la colección de hojas del libro activo
//coleccionHojas = aplicacionExcel.OlePropertyGet("Worksheets");
coleccionHojas = libro.Exec(PropertyGet("Worksheets"));


//
// HOJA ACTIVA
//

// coger la hoja activa de la colección de hojas
//hoja=aplicacionExcel.Exec(PropertyGet("ActiveSheet"));
hoja = coleccionHojas.Exec(PropertyGet("Item") << 1);


if (hoja.IsEmpty())
ShowMessage("No hay ninguna hoja activa");
else
{

// ver nombre a una hoja
EnombreHoja->Text=hoja.Exec(PropertyGet("Name"));


//
// CELDAS
//



int fila; // índice a la fila actual
int ultimaFila; // índice a la última fila que tiene datos (no la conozco inicialmente)
int columna;
int ultimaColumna;
Variant ultimaCelda; // contiene la última celda
String valor; // contiene valor de una celda (son de tipo String)

// indico la primera fila que tiene datos (se supone que lo se)
fila=1;
columna=1;

// Busca la última fila que tiene datos:

// coger la coleccion de celdas
celdas=hoja.Exec(PropertyGet("Cells"));

// coger la última celda con datos
ultimaCelda=celdas.Exec(Function("SpecialCells")<<11);

// fila de la ultima celda
ultimaFila=ultimaCelda.Exec(PropertyGet("Row"));
EnumFilas->Text=ultimaFila;

// coger la última columna ?
ultimaColumna=3;

Panel1->Color = clRed;

for (fila=1; fila<=ultimaFila;fila++)
for (columna=1; columna<=ultimaColumna;columna++)
{
Application->ProcessMessages();

// leo valor celda (fila =fila, columna = columna)
valor=hoja.Exec(PropertyGet("Cells")<<fila<<columna);

Efila->Text=fila;
Ecolumna->Text=columna;

// tratar como números

try
{
// EvalorInt->Text=StrToInt(valor);
EvalorInt->Text=valor.ToDouble();
}
catch (Exception &EConvertError)
{
EvalorInt->Text="NO ES UN NUMERO";
//Application->ShowException(&EConvertError);
}

// tratar como texto

if(valor.IsEmpty())
{
EvalorString->Text="VOID";
EvalorChar->Text="VOID";
}
else
{
EvalorString->Text=valor;
EvalorChar->Text=valor.c_str();
}

_sleep(1);
}

_sleep(1);
Panel1->Color = clGreen;

//
// CERRAR
//

cerrarExcel();
} // fin if hoja isEmpty

}
catch (Exception &exception)
{
BimportarExcel->Enabled=true;
BexportarExcel->Enabled=true;
cerrarExcel();
return;
}

} // fin if OPENDIALOG1 ...

BimportarExcel->Enabled=true;
BexportarExcel->Enabled=true;
}



//---------------------------------------------------------------------------
//-------------------- Exportar un archivo de Excel ---------------------
//---------------------------------------------------------------------------

void __fastcall TForm1::BexportarExcelClick(TObject *Sender)
{
BexportarExcel->Enabled=false;
BimportarExcel->Enabled=false;


//
// Empezamos con EXCEL
//
try
{
Pabierto->Color=clYellow;
Pabierto->Caption=mensajeAlerta;

//Abro la aplicación Excel y la hago visible
aplicacionExcel=CreateOleObject("Excel.Application");
//aplicacionExcel.Exec(PropertySet("Visible")<<true);
}
catch (Exception &exception) // no llegó a abrirse
{
Application->MessageBox(
"Esta aplicación necesita Excel 97 o superior",
"Aviso...",MB_ICONSTOP);
BimportarExcel->Enabled=true;
BexportarExcel->Enabled=true;
return;
}

//
// LIBROS
//

// añadir una colección de libros
coleccionLibros=aplicacionExcel.OlePropertyGet("Workbooks");
coleccionLibros.OleProcedure("Add");

// ... o así directamente:
//aplicacionExcel.OlePropertyGet("Workbooks").OleProcedure("Add");



//
// LIBRO ACTIVO
//

// coger el primer libro de la aplicacion
libro = coleccionLibros.Exec(PropertyGet("Item") << 1);



//
// HOJAS
//

// coger la colección de hojas del libro activo
coleccionHojas = libro.OlePropertyGet("Worksheets");

// ... o así directamente:
//coleccionHojas = aplicacionExcel.OlePropertyGet("Worksheets");



//
// HOJA ACTIVA
//

// coger la hoja activa de la colección de hojas

//hoja=aplicacionExcel.Exec(PropertyGet("ActiveSheet"));
hoja = coleccionHojas.Exec(PropertyGet("Item") << 1);

// ... o añadir una hoja a una colección
if (hoja.IsEmpty())
hoja=coleccionHojas.Exec(Function("Add"));

// darle nombre
hoja.Exec(PropertySet("Name")<< "hoja nueva");


//
// CELDAS: ESCRIBIR DATOS EN HOJA ACTIVA
//

//---------------------------------------------------------------------------
//---------------------------------------------------------------------------


//
// CELDAS
//



int fila; // índice a la fila actual
int ultimaFila; // índice a la última fila que tiene datos
int columna;
int ultimaColumna;
double doble;
char cadenaDoble [100];
ultimaFila = 2;
ultimaColumna = 6;

Panel1->Color = clRed;

//
// FORMA 1
//
// hoja.Exec(PropertySet("Cells") << Fila << Columna << valorTipoString);
//


for (fila=1; fila<=ultimaFila;fila++)
for (columna=1; columna<=ultimaColumna;columna++)
{
Application->ProcessMessages(); // ??

switch (columna)
{
case 2 : /* cadenas de texto */
hoja.Exec(PropertySet("Cells") << fila << columna << "COLUMNA2");
break;
case 3,5: /* enteros */
hoja.Exec(PropertySet("Cells") << fila << columna << String(columna));
break;
default: /* reales */
doble=10.67;
sprintf(cadenaDoble,"%le", doble);// convierto el double en cadena caracteres

/*
EvalorInt->Text=doble;
EvalorChar->Text=cadenaDoble;
EvalorString->Text=String(cadenaDoble);
_sleep(1);
*/

hoja.Exec(PropertySet("Cells") << fila << columna << cadenaDoble);
break;

}

Efila->Text=fila;
Ecolumna->Text=columna;
}



//
// FORMA 2
//
// trabajando con reangos de celdas dentro de una hoja
//


Variant VRange;

//-------- Escribe texto en las celdas 3A - 5C
VRange = hoja.Exec(PropertyGet("Range") << "A3");
VRange.Exec(PropertySet("Value") << "CeldaA3");
VRange = hoja.Exec(PropertyGet("Range") << "A4");
VRange.Exec(PropertySet("Value") << "CeldaA4");
VRange = hoja.Exec(PropertyGet("Range") << "A5");
VRange.Exec(PropertySet("Value") << "CeldaA5");
//------
VRange = hoja.Exec(PropertyGet("Range") << "B3");
VRange.Exec(PropertySet("Value") << "CeldaB3");
VRange = hoja.Exec(PropertyGet("Range") << "B4");
VRange.Exec(PropertySet("Value") << "CeldaB2");
VRange = hoja.Exec(PropertyGet("Range") << "B5");
VRange.Exec(PropertySet("Value") << "CeldaB3");
//------
VRange = hoja.Exec(PropertyGet("Range") << "C3");
VRange.Exec(PropertySet("Value") << "CeldaC3");
VRange = hoja.Exec(PropertyGet("Range") << "C4");
VRange.Exec(PropertySet("Value") << "CeldaC4");
VRange = hoja.Exec(PropertyGet("Range") << "C5");
VRange.Exec(PropertySet("Value") << "CeldaC5");

//-------- Borra las primeras 2 x 2 celdas
VRange = hoja.Exec(PropertyGet("Range") << "A1:B2");
VRange.Exec(Function("ClearContents"));


Panel1->Color = clGreen;





//---------------------------------------------------------------------------
//---------------------------------------------------------------------------

//
// GUARDAR EL NUEVO FICHERO
//


char * fSalida="salida.xls"; // me lo salva en la carpeta Mis Documentos


// Opción 1.- DIRECTAMENTE METIENDO EL PATH

// si excel visible -> cerrar directamente desde excel -> no llamar a cerrarExcel())
// si excel no visible -> cerrarExcel()

/*
try
{
libro.Exec(Procedure("SaveAs") << fSalida); // path de "Mis documentos"
}catch (Exception &exception) // no llegó a abrirse
{
// **1**
// deshabilitar los mensaje se excel
// pq si decido no realizar el save as anterior, el excel muestra un mensaje
// preguntando si se quiere savar el libro creado
aplicacionExcel.Exec(PropertySet("DisplayAlerts") << false);
}
*/


// Opción 2.- salvar a través del excel (cono su savedialog) -> por **1**

// NO HAY QUE HACER NADA -> LO HACE SOLO EL EXCEL (objeto ExcelApplication)
// antes de ejecutar el código de cerrarExcel

cerrarExcel();

BexportarExcel->Enabled=true;
BimportarExcel->Enabled=true;

}
//---------------------------------------------------------------------------